File: | include/llvm/Support/Error.h |
Warning: | line 200, column 5 Potential leak of memory pointed to by 'Payload._M_t._M_head_impl' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file defines the ASTImporter class which imports AST nodes from one | |||
10 | // context into another context. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "clang/AST/ASTImporter.h" | |||
15 | #include "clang/AST/ASTImporterLookupTable.h" | |||
16 | #include "clang/AST/ASTContext.h" | |||
17 | #include "clang/AST/ASTDiagnostic.h" | |||
18 | #include "clang/AST/ASTStructuralEquivalence.h" | |||
19 | #include "clang/AST/Attr.h" | |||
20 | #include "clang/AST/Decl.h" | |||
21 | #include "clang/AST/DeclAccessPair.h" | |||
22 | #include "clang/AST/DeclBase.h" | |||
23 | #include "clang/AST/DeclCXX.h" | |||
24 | #include "clang/AST/DeclFriend.h" | |||
25 | #include "clang/AST/DeclGroup.h" | |||
26 | #include "clang/AST/DeclObjC.h" | |||
27 | #include "clang/AST/DeclTemplate.h" | |||
28 | #include "clang/AST/DeclVisitor.h" | |||
29 | #include "clang/AST/DeclarationName.h" | |||
30 | #include "clang/AST/Expr.h" | |||
31 | #include "clang/AST/ExprCXX.h" | |||
32 | #include "clang/AST/ExprObjC.h" | |||
33 | #include "clang/AST/ExternalASTSource.h" | |||
34 | #include "clang/AST/LambdaCapture.h" | |||
35 | #include "clang/AST/NestedNameSpecifier.h" | |||
36 | #include "clang/AST/OperationKinds.h" | |||
37 | #include "clang/AST/Stmt.h" | |||
38 | #include "clang/AST/StmtCXX.h" | |||
39 | #include "clang/AST/StmtObjC.h" | |||
40 | #include "clang/AST/StmtVisitor.h" | |||
41 | #include "clang/AST/TemplateBase.h" | |||
42 | #include "clang/AST/TemplateName.h" | |||
43 | #include "clang/AST/Type.h" | |||
44 | #include "clang/AST/TypeLoc.h" | |||
45 | #include "clang/AST/TypeVisitor.h" | |||
46 | #include "clang/AST/UnresolvedSet.h" | |||
47 | #include "clang/Basic/ExceptionSpecificationType.h" | |||
48 | #include "clang/Basic/FileManager.h" | |||
49 | #include "clang/Basic/IdentifierTable.h" | |||
50 | #include "clang/Basic/LLVM.h" | |||
51 | #include "clang/Basic/LangOptions.h" | |||
52 | #include "clang/Basic/SourceLocation.h" | |||
53 | #include "clang/Basic/SourceManager.h" | |||
54 | #include "clang/Basic/Specifiers.h" | |||
55 | #include "llvm/ADT/APSInt.h" | |||
56 | #include "llvm/ADT/ArrayRef.h" | |||
57 | #include "llvm/ADT/DenseMap.h" | |||
58 | #include "llvm/ADT/None.h" | |||
59 | #include "llvm/ADT/Optional.h" | |||
60 | #include "llvm/ADT/STLExtras.h" | |||
61 | #include "llvm/ADT/SmallVector.h" | |||
62 | #include "llvm/Support/Casting.h" | |||
63 | #include "llvm/Support/ErrorHandling.h" | |||
64 | #include "llvm/Support/MemoryBuffer.h" | |||
65 | #include <algorithm> | |||
66 | #include <cassert> | |||
67 | #include <cstddef> | |||
68 | #include <memory> | |||
69 | #include <type_traits> | |||
70 | #include <utility> | |||
71 | ||||
72 | namespace clang { | |||
73 | ||||
74 | using llvm::make_error; | |||
75 | using llvm::Error; | |||
76 | using llvm::Expected; | |||
77 | using ExpectedType = llvm::Expected<QualType>; | |||
78 | using ExpectedStmt = llvm::Expected<Stmt *>; | |||
79 | using ExpectedExpr = llvm::Expected<Expr *>; | |||
80 | using ExpectedDecl = llvm::Expected<Decl *>; | |||
81 | using ExpectedSLoc = llvm::Expected<SourceLocation>; | |||
82 | ||||
83 | std::string ImportError::toString() const { | |||
84 | // FIXME: Improve error texts. | |||
85 | switch (Error) { | |||
86 | case NameConflict: | |||
87 | return "NameConflict"; | |||
88 | case UnsupportedConstruct: | |||
89 | return "UnsupportedConstruct"; | |||
90 | case Unknown: | |||
91 | return "Unknown error"; | |||
92 | } | |||
93 | llvm_unreachable("Invalid error code.")::llvm::llvm_unreachable_internal("Invalid error code.", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 93); | |||
94 | return "Invalid error code."; | |||
95 | } | |||
96 | ||||
97 | void ImportError::log(raw_ostream &OS) const { | |||
98 | OS << toString(); | |||
99 | } | |||
100 | ||||
101 | std::error_code ImportError::convertToErrorCode() const { | |||
102 | llvm_unreachable("Function not implemented.")::llvm::llvm_unreachable_internal("Function not implemented." , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 102); | |||
103 | } | |||
104 | ||||
105 | char ImportError::ID; | |||
106 | ||||
107 | template <class T> | |||
108 | SmallVector<Decl *, 2> | |||
109 | getCanonicalForwardRedeclChain(Redeclarable<T>* D) { | |||
110 | SmallVector<Decl *, 2> Redecls; | |||
111 | for (auto *R : D->getFirstDecl()->redecls()) { | |||
112 | if (R != D->getFirstDecl()) | |||
113 | Redecls.push_back(R); | |||
114 | } | |||
115 | Redecls.push_back(D->getFirstDecl()); | |||
116 | std::reverse(Redecls.begin(), Redecls.end()); | |||
117 | return Redecls; | |||
118 | } | |||
119 | ||||
120 | SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) { | |||
121 | if (auto *FD = dyn_cast<FunctionDecl>(D)) | |||
122 | return getCanonicalForwardRedeclChain<FunctionDecl>(FD); | |||
123 | if (auto *VD = dyn_cast<VarDecl>(D)) | |||
124 | return getCanonicalForwardRedeclChain<VarDecl>(VD); | |||
125 | if (auto *TD = dyn_cast<TagDecl>(D)) | |||
126 | return getCanonicalForwardRedeclChain<TagDecl>(TD); | |||
127 | llvm_unreachable("Bad declaration kind")::llvm::llvm_unreachable_internal("Bad declaration kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 127); | |||
128 | } | |||
129 | ||||
130 | void updateFlags(const Decl *From, Decl *To) { | |||
131 | // Check if some flags or attrs are new in 'From' and copy into 'To'. | |||
132 | // FIXME: Other flags or attrs? | |||
133 | if (From->isUsed(false) && !To->isUsed(false)) | |||
134 | To->setIsUsed(); | |||
135 | } | |||
136 | ||||
137 | class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>, | |||
138 | public DeclVisitor<ASTNodeImporter, ExpectedDecl>, | |||
139 | public StmtVisitor<ASTNodeImporter, ExpectedStmt> { | |||
140 | ASTImporter &Importer; | |||
141 | ||||
142 | // Use this instead of Importer.importInto . | |||
143 | template <typename ImportT> | |||
144 | LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT &To, const ImportT &From) { | |||
145 | return Importer.importInto(To, From); | |||
146 | } | |||
147 | ||||
148 | // Use this to import pointers of specific type. | |||
149 | template <typename ImportT> | |||
150 | LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT *&To, ImportT *From) { | |||
151 | auto ToOrErr = Importer.Import(From); | |||
152 | if (ToOrErr) | |||
153 | To = cast_or_null<ImportT>(*ToOrErr); | |||
154 | return ToOrErr.takeError(); | |||
155 | } | |||
156 | ||||
157 | // Call the import function of ASTImporter for a baseclass of type `T` and | |||
158 | // cast the return value to `T`. | |||
159 | template <typename T> | |||
160 | Expected<T *> import(T *From) { | |||
161 | auto ToOrErr = Importer.Import(From); | |||
162 | if (!ToOrErr) | |||
163 | return ToOrErr.takeError(); | |||
164 | return cast_or_null<T>(*ToOrErr); | |||
165 | } | |||
166 | ||||
167 | template <typename T> | |||
168 | Expected<T *> import(const T *From) { | |||
169 | return import(const_cast<T *>(From)); | |||
170 | } | |||
171 | ||||
172 | // Call the import function of ASTImporter for type `T`. | |||
173 | template <typename T> | |||
174 | Expected<T> import(const T &From) { | |||
175 | return Importer.Import(From); | |||
176 | } | |||
177 | ||||
178 | // Import an Optional<T> by importing the contained T, if any. | |||
179 | template<typename T> | |||
180 | Expected<Optional<T>> import(Optional<T> From) { | |||
181 | if (!From) | |||
182 | return Optional<T>(); | |||
183 | return import(*From); | |||
184 | } | |||
185 | ||||
186 | template <class T> | |||
187 | Expected<std::tuple<T>> | |||
188 | importSeq(const T &From) { | |||
189 | Expected<T> ToOrErr = import(From); | |||
190 | if (!ToOrErr) | |||
191 | return ToOrErr.takeError(); | |||
192 | return std::make_tuple<T>(std::move(*ToOrErr)); | |||
193 | } | |||
194 | ||||
195 | // Import multiple objects with a single function call. | |||
196 | // This should work for every type for which a variant of `import` exists. | |||
197 | // The arguments are processed from left to right and import is stopped on | |||
198 | // first error. | |||
199 | template <class THead, class... TTail> | |||
200 | Expected<std::tuple<THead, TTail...>> | |||
201 | importSeq(const THead &FromHead, const TTail &...FromTail) { | |||
202 | Expected<std::tuple<THead>> ToHeadOrErr = importSeq(FromHead); | |||
203 | if (!ToHeadOrErr) | |||
204 | return ToHeadOrErr.takeError(); | |||
205 | Expected<std::tuple<TTail...>> ToTailOrErr = importSeq(FromTail...); | |||
206 | if (!ToTailOrErr) | |||
207 | return ToTailOrErr.takeError(); | |||
208 | return std::tuple_cat(*ToHeadOrErr, *ToTailOrErr); | |||
209 | } | |||
210 | ||||
211 | // Wrapper for an overload set. | |||
212 | template <typename ToDeclT> struct CallOverloadedCreateFun { | |||
213 | template <typename... Args> | |||
214 | auto operator()(Args &&... args) | |||
215 | -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) { | |||
216 | return ToDeclT::Create(std::forward<Args>(args)...); | |||
217 | } | |||
218 | }; | |||
219 | ||||
220 | // Always use these functions to create a Decl during import. There are | |||
221 | // certain tasks which must be done after the Decl was created, e.g. we | |||
222 | // must immediately register that as an imported Decl. The parameter `ToD` | |||
223 | // will be set to the newly created Decl or if had been imported before | |||
224 | // then to the already imported Decl. Returns a bool value set to true if | |||
225 | // the `FromD` had been imported before. | |||
226 | template <typename ToDeclT, typename FromDeclT, typename... Args> | |||
227 | LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, | |||
228 | Args &&... args) { | |||
229 | // There may be several overloads of ToDeclT::Create. We must make sure | |||
230 | // to call the one which would be chosen by the arguments, thus we use a | |||
231 | // wrapper for the overload set. | |||
232 | CallOverloadedCreateFun<ToDeclT> OC; | |||
233 | return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, | |||
234 | std::forward<Args>(args)...); | |||
235 | } | |||
236 | // Use this overload if a special Type is needed to be created. E.g if we | |||
237 | // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl` | |||
238 | // then: | |||
239 | // TypedefNameDecl *ToTypedef; | |||
240 | // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...); | |||
241 | template <typename NewDeclT, typename ToDeclT, typename FromDeclT, | |||
242 | typename... Args> | |||
243 | LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, | |||
244 | Args &&... args) { | |||
245 | CallOverloadedCreateFun<NewDeclT> OC; | |||
246 | return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, | |||
247 | std::forward<Args>(args)...); | |||
248 | } | |||
249 | // Use this version if a special create function must be | |||
250 | // used, e.g. CXXRecordDecl::CreateLambda . | |||
251 | template <typename ToDeclT, typename CreateFunT, typename FromDeclT, | |||
252 | typename... Args> | |||
253 | LLVM_NODISCARD[[clang::warn_unused_result]] bool | |||
254 | GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun, | |||
255 | FromDeclT *FromD, Args &&... args) { | |||
256 | // FIXME: This code is needed later. | |||
257 | //if (Importer.getImportDeclErrorIfAny(FromD)) { | |||
258 | // ToD = nullptr; | |||
259 | // return true; // Already imported but with error. | |||
260 | //} | |||
261 | ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD)); | |||
262 | if (ToD) | |||
263 | return true; // Already imported. | |||
264 | ToD = CreateFun(std::forward<Args>(args)...); | |||
265 | // Keep track of imported Decls. | |||
266 | Importer.RegisterImportedDecl(FromD, ToD); | |||
267 | InitializeImportedDecl(FromD, ToD); | |||
268 | return false; // A new Decl is created. | |||
269 | } | |||
270 | ||||
271 | void InitializeImportedDecl(Decl *FromD, Decl *ToD) { | |||
272 | ToD->IdentifierNamespace = FromD->IdentifierNamespace; | |||
273 | if (FromD->hasAttrs()) | |||
274 | for (const Attr *FromAttr : FromD->getAttrs()) { | |||
275 | // FIXME: Return of the error here is not possible until store of | |||
276 | // import errors is implemented. | |||
277 | auto ToAttrOrErr = import(FromAttr); | |||
278 | if (ToAttrOrErr) | |||
279 | ToD->addAttr(*ToAttrOrErr); | |||
280 | else | |||
281 | llvm::consumeError(ToAttrOrErr.takeError()); | |||
282 | } | |||
283 | if (FromD->isUsed()) | |||
284 | ToD->setIsUsed(); | |||
285 | if (FromD->isImplicit()) | |||
286 | ToD->setImplicit(); | |||
287 | } | |||
288 | ||||
289 | // Check if we have found an existing definition. Returns with that | |||
290 | // definition if yes, otherwise returns null. | |||
291 | Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) { | |||
292 | const FunctionDecl *Definition = nullptr; | |||
293 | if (D->doesThisDeclarationHaveABody() && | |||
294 | FoundFunction->hasBody(Definition)) | |||
295 | return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition)); | |||
296 | return nullptr; | |||
297 | } | |||
298 | ||||
299 | public: | |||
300 | explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} | |||
301 | ||||
302 | using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit; | |||
303 | using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit; | |||
304 | using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit; | |||
305 | ||||
306 | // Importing types | |||
307 | ExpectedType VisitType(const Type *T); | |||
308 | ExpectedType VisitAtomicType(const AtomicType *T); | |||
309 | ExpectedType VisitBuiltinType(const BuiltinType *T); | |||
310 | ExpectedType VisitDecayedType(const DecayedType *T); | |||
311 | ExpectedType VisitComplexType(const ComplexType *T); | |||
312 | ExpectedType VisitPointerType(const PointerType *T); | |||
313 | ExpectedType VisitBlockPointerType(const BlockPointerType *T); | |||
314 | ExpectedType VisitLValueReferenceType(const LValueReferenceType *T); | |||
315 | ExpectedType VisitRValueReferenceType(const RValueReferenceType *T); | |||
316 | ExpectedType VisitMemberPointerType(const MemberPointerType *T); | |||
317 | ExpectedType VisitConstantArrayType(const ConstantArrayType *T); | |||
318 | ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T); | |||
319 | ExpectedType VisitVariableArrayType(const VariableArrayType *T); | |||
320 | ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T); | |||
321 | // FIXME: DependentSizedExtVectorType | |||
322 | ExpectedType VisitVectorType(const VectorType *T); | |||
323 | ExpectedType VisitExtVectorType(const ExtVectorType *T); | |||
324 | ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T); | |||
325 | ExpectedType VisitFunctionProtoType(const FunctionProtoType *T); | |||
326 | ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T); | |||
327 | ExpectedType VisitParenType(const ParenType *T); | |||
328 | ExpectedType VisitTypedefType(const TypedefType *T); | |||
329 | ExpectedType VisitTypeOfExprType(const TypeOfExprType *T); | |||
330 | // FIXME: DependentTypeOfExprType | |||
331 | ExpectedType VisitTypeOfType(const TypeOfType *T); | |||
332 | ExpectedType VisitDecltypeType(const DecltypeType *T); | |||
333 | ExpectedType VisitUnaryTransformType(const UnaryTransformType *T); | |||
334 | ExpectedType VisitAutoType(const AutoType *T); | |||
335 | ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T); | |||
336 | // FIXME: DependentDecltypeType | |||
337 | ExpectedType VisitRecordType(const RecordType *T); | |||
338 | ExpectedType VisitEnumType(const EnumType *T); | |||
339 | ExpectedType VisitAttributedType(const AttributedType *T); | |||
340 | ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T); | |||
341 | ExpectedType VisitSubstTemplateTypeParmType( | |||
342 | const SubstTemplateTypeParmType *T); | |||
343 | ExpectedType VisitTemplateSpecializationType( | |||
344 | const TemplateSpecializationType *T); | |||
345 | ExpectedType VisitElaboratedType(const ElaboratedType *T); | |||
346 | ExpectedType VisitDependentNameType(const DependentNameType *T); | |||
347 | ExpectedType VisitPackExpansionType(const PackExpansionType *T); | |||
348 | ExpectedType VisitDependentTemplateSpecializationType( | |||
349 | const DependentTemplateSpecializationType *T); | |||
350 | ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T); | |||
351 | ExpectedType VisitObjCObjectType(const ObjCObjectType *T); | |||
352 | ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); | |||
353 | ||||
354 | // Importing declarations | |||
355 | Error ImportDeclParts( | |||
356 | NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, | |||
357 | DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc); | |||
358 | Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); | |||
359 | Error ImportDeclarationNameLoc( | |||
360 | const DeclarationNameInfo &From, DeclarationNameInfo &To); | |||
361 | Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false); | |||
362 | Error ImportDeclContext( | |||
363 | Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC); | |||
364 | Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To); | |||
365 | ||||
366 | Expected<CXXCastPath> ImportCastPath(CastExpr *E); | |||
367 | ||||
368 | using Designator = DesignatedInitExpr::Designator; | |||
369 | ||||
370 | /// What we should import from the definition. | |||
371 | enum ImportDefinitionKind { | |||
372 | /// Import the default subset of the definition, which might be | |||
373 | /// nothing (if minimal import is set) or might be everything (if minimal | |||
374 | /// import is not set). | |||
375 | IDK_Default, | |||
376 | /// Import everything. | |||
377 | IDK_Everything, | |||
378 | /// Import only the bare bones needed to establish a valid | |||
379 | /// DeclContext. | |||
380 | IDK_Basic | |||
381 | }; | |||
382 | ||||
383 | bool shouldForceImportDeclContext(ImportDefinitionKind IDK) { | |||
384 | return IDK == IDK_Everything || | |||
385 | (IDK == IDK_Default && !Importer.isMinimalImport()); | |||
386 | } | |||
387 | ||||
388 | Error ImportInitializer(VarDecl *From, VarDecl *To); | |||
389 | Error ImportDefinition( | |||
390 | RecordDecl *From, RecordDecl *To, | |||
391 | ImportDefinitionKind Kind = IDK_Default); | |||
392 | Error ImportDefinition( | |||
393 | EnumDecl *From, EnumDecl *To, | |||
394 | ImportDefinitionKind Kind = IDK_Default); | |||
395 | Error ImportDefinition( | |||
396 | ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, | |||
397 | ImportDefinitionKind Kind = IDK_Default); | |||
398 | Error ImportDefinition( | |||
399 | ObjCProtocolDecl *From, ObjCProtocolDecl *To, | |||
400 | ImportDefinitionKind Kind = IDK_Default); | |||
401 | Error ImportTemplateArguments( | |||
402 | const TemplateArgument *FromArgs, unsigned NumFromArgs, | |||
403 | SmallVectorImpl<TemplateArgument> &ToArgs); | |||
404 | Expected<TemplateArgument> | |||
405 | ImportTemplateArgument(const TemplateArgument &From); | |||
406 | ||||
407 | template <typename InContainerTy> | |||
408 | Error ImportTemplateArgumentListInfo( | |||
409 | const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo); | |||
410 | ||||
411 | template<typename InContainerTy> | |||
412 | Error ImportTemplateArgumentListInfo( | |||
413 | SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, | |||
414 | const InContainerTy &Container, TemplateArgumentListInfo &Result); | |||
415 | ||||
416 | using TemplateArgsTy = SmallVector<TemplateArgument, 8>; | |||
417 | using FunctionTemplateAndArgsTy = | |||
418 | std::tuple<FunctionTemplateDecl *, TemplateArgsTy>; | |||
419 | Expected<FunctionTemplateAndArgsTy> | |||
420 | ImportFunctionTemplateWithTemplateArgsFromSpecialization( | |||
421 | FunctionDecl *FromFD); | |||
422 | Error ImportTemplateParameterLists(const DeclaratorDecl *FromD, | |||
423 | DeclaratorDecl *ToD); | |||
424 | ||||
425 | Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); | |||
426 | ||||
427 | Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD); | |||
428 | ||||
429 | template <typename T> | |||
430 | bool hasSameVisibilityContext(T *Found, T *From); | |||
431 | ||||
432 | bool IsStructuralMatch(Decl *From, Decl *To, bool Complain); | |||
433 | bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, | |||
434 | bool Complain = true); | |||
435 | bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, | |||
436 | bool Complain = true); | |||
437 | bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord); | |||
438 | bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC); | |||
439 | bool IsStructuralMatch(FunctionTemplateDecl *From, | |||
440 | FunctionTemplateDecl *To); | |||
441 | bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To); | |||
442 | bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To); | |||
443 | bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To); | |||
444 | ExpectedDecl VisitDecl(Decl *D); | |||
445 | ExpectedDecl VisitImportDecl(ImportDecl *D); | |||
446 | ExpectedDecl VisitEmptyDecl(EmptyDecl *D); | |||
447 | ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D); | |||
448 | ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D); | |||
449 | ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D); | |||
450 | ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D); | |||
451 | ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D); | |||
452 | ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias); | |||
453 | ExpectedDecl VisitTypedefDecl(TypedefDecl *D); | |||
454 | ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D); | |||
455 | ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); | |||
456 | ExpectedDecl VisitLabelDecl(LabelDecl *D); | |||
457 | ExpectedDecl VisitEnumDecl(EnumDecl *D); | |||
458 | ExpectedDecl VisitRecordDecl(RecordDecl *D); | |||
459 | ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D); | |||
460 | ExpectedDecl VisitFunctionDecl(FunctionDecl *D); | |||
461 | ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D); | |||
462 | ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D); | |||
463 | ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D); | |||
464 | ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D); | |||
465 | ExpectedDecl VisitFieldDecl(FieldDecl *D); | |||
466 | ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D); | |||
467 | ExpectedDecl VisitFriendDecl(FriendDecl *D); | |||
468 | ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D); | |||
469 | ExpectedDecl VisitVarDecl(VarDecl *D); | |||
470 | ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D); | |||
471 | ExpectedDecl VisitParmVarDecl(ParmVarDecl *D); | |||
472 | ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D); | |||
473 | ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); | |||
474 | ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D); | |||
475 | ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D); | |||
476 | ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D); | |||
477 | ExpectedDecl VisitUsingDecl(UsingDecl *D); | |||
478 | ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D); | |||
479 | ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D); | |||
480 | ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); | |||
481 | ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); | |||
482 | ||||
483 | Expected<ObjCTypeParamList *> | |||
484 | ImportObjCTypeParamList(ObjCTypeParamList *list); | |||
485 | ||||
486 | ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); | |||
487 | ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); | |||
488 | ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D); | |||
489 | ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D); | |||
490 | ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); | |||
491 | ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); | |||
492 | ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); | |||
493 | ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); | |||
494 | ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D); | |||
495 | ExpectedDecl VisitClassTemplateSpecializationDecl( | |||
496 | ClassTemplateSpecializationDecl *D); | |||
497 | ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D); | |||
498 | ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D); | |||
499 | ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D); | |||
500 | ||||
501 | // Importing statements | |||
502 | ExpectedStmt VisitStmt(Stmt *S); | |||
503 | ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S); | |||
504 | ExpectedStmt VisitDeclStmt(DeclStmt *S); | |||
505 | ExpectedStmt VisitNullStmt(NullStmt *S); | |||
506 | ExpectedStmt VisitCompoundStmt(CompoundStmt *S); | |||
507 | ExpectedStmt VisitCaseStmt(CaseStmt *S); | |||
508 | ExpectedStmt VisitDefaultStmt(DefaultStmt *S); | |||
509 | ExpectedStmt VisitLabelStmt(LabelStmt *S); | |||
510 | ExpectedStmt VisitAttributedStmt(AttributedStmt *S); | |||
511 | ExpectedStmt VisitIfStmt(IfStmt *S); | |||
512 | ExpectedStmt VisitSwitchStmt(SwitchStmt *S); | |||
513 | ExpectedStmt VisitWhileStmt(WhileStmt *S); | |||
514 | ExpectedStmt VisitDoStmt(DoStmt *S); | |||
515 | ExpectedStmt VisitForStmt(ForStmt *S); | |||
516 | ExpectedStmt VisitGotoStmt(GotoStmt *S); | |||
517 | ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S); | |||
518 | ExpectedStmt VisitContinueStmt(ContinueStmt *S); | |||
519 | ExpectedStmt VisitBreakStmt(BreakStmt *S); | |||
520 | ExpectedStmt VisitReturnStmt(ReturnStmt *S); | |||
521 | // FIXME: MSAsmStmt | |||
522 | // FIXME: SEHExceptStmt | |||
523 | // FIXME: SEHFinallyStmt | |||
524 | // FIXME: SEHTryStmt | |||
525 | // FIXME: SEHLeaveStmt | |||
526 | // FIXME: CapturedStmt | |||
527 | ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S); | |||
528 | ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S); | |||
529 | ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S); | |||
530 | // FIXME: MSDependentExistsStmt | |||
531 | ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); | |||
532 | ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); | |||
533 | ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S); | |||
534 | ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S); | |||
535 | ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); | |||
536 | ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); | |||
537 | ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); | |||
538 | ||||
539 | // Importing expressions | |||
540 | ExpectedStmt VisitExpr(Expr *E); | |||
541 | ExpectedStmt VisitVAArgExpr(VAArgExpr *E); | |||
542 | ExpectedStmt VisitChooseExpr(ChooseExpr *E); | |||
543 | ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E); | |||
544 | ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E); | |||
545 | ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E); | |||
546 | ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); | |||
547 | ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E); | |||
548 | ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E); | |||
549 | ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E); | |||
550 | ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E); | |||
551 | ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E); | |||
552 | ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E); | |||
553 | ExpectedStmt VisitStringLiteral(StringLiteral *E); | |||
554 | ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E); | |||
555 | ExpectedStmt VisitAtomicExpr(AtomicExpr *E); | |||
556 | ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E); | |||
557 | ExpectedStmt VisitConstantExpr(ConstantExpr *E); | |||
558 | ExpectedStmt VisitParenExpr(ParenExpr *E); | |||
559 | ExpectedStmt VisitParenListExpr(ParenListExpr *E); | |||
560 | ExpectedStmt VisitStmtExpr(StmtExpr *E); | |||
561 | ExpectedStmt VisitUnaryOperator(UnaryOperator *E); | |||
562 | ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); | |||
563 | ExpectedStmt VisitBinaryOperator(BinaryOperator *E); | |||
564 | ExpectedStmt VisitConditionalOperator(ConditionalOperator *E); | |||
565 | ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E); | |||
566 | ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E); | |||
567 | ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); | |||
568 | ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E); | |||
569 | ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E); | |||
570 | ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E); | |||
571 | ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E); | |||
572 | ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E); | |||
573 | ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE); | |||
574 | ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E); | |||
575 | ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E); | |||
576 | ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E); | |||
577 | ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); | |||
578 | ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); | |||
579 | ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); | |||
580 | ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); | |||
581 | ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E); | |||
582 | ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E); | |||
583 | ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E); | |||
584 | ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E); | |||
585 | ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E); | |||
586 | ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E); | |||
587 | ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); | |||
588 | ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); | |||
589 | ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); | |||
590 | ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E); | |||
591 | ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E); | |||
592 | ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E); | |||
593 | ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E); | |||
594 | ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E); | |||
595 | ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); | |||
596 | ExpectedStmt VisitMemberExpr(MemberExpr *E); | |||
597 | ExpectedStmt VisitCallExpr(CallExpr *E); | |||
598 | ExpectedStmt VisitLambdaExpr(LambdaExpr *LE); | |||
599 | ExpectedStmt VisitInitListExpr(InitListExpr *E); | |||
600 | ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); | |||
601 | ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E); | |||
602 | ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E); | |||
603 | ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E); | |||
604 | ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E); | |||
605 | ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E); | |||
606 | ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E); | |||
607 | ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E); | |||
608 | ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E); | |||
609 | ||||
610 | template<typename IIter, typename OIter> | |||
611 | Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) { | |||
612 | using ItemT = typename std::remove_reference<decltype(*Obegin)>::type; | |||
613 | for (; Ibegin != Iend; ++Ibegin, ++Obegin) { | |||
614 | Expected<ItemT> ToOrErr = import(*Ibegin); | |||
615 | if (!ToOrErr) | |||
616 | return ToOrErr.takeError(); | |||
617 | *Obegin = *ToOrErr; | |||
618 | } | |||
619 | return Error::success(); | |||
620 | } | |||
621 | ||||
622 | // Import every item from a container structure into an output container. | |||
623 | // If error occurs, stops at first error and returns the error. | |||
624 | // The output container should have space for all needed elements (it is not | |||
625 | // expanded, new items are put into from the beginning). | |||
626 | template<typename InContainerTy, typename OutContainerTy> | |||
627 | Error ImportContainerChecked( | |||
628 | const InContainerTy &InContainer, OutContainerTy &OutContainer) { | |||
629 | return ImportArrayChecked( | |||
630 | InContainer.begin(), InContainer.end(), OutContainer.begin()); | |||
631 | } | |||
632 | ||||
633 | template<typename InContainerTy, typename OIter> | |||
634 | Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) { | |||
635 | return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin); | |||
636 | } | |||
637 | ||||
638 | void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod); | |||
639 | ||||
640 | Expected<FunctionDecl *> FindFunctionTemplateSpecialization( | |||
641 | FunctionDecl *FromFD); | |||
642 | }; | |||
643 | ||||
644 | template <typename InContainerTy> | |||
645 | Error ASTNodeImporter::ImportTemplateArgumentListInfo( | |||
646 | SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, | |||
647 | const InContainerTy &Container, TemplateArgumentListInfo &Result) { | |||
648 | auto ToLAngleLocOrErr = import(FromLAngleLoc); | |||
649 | if (!ToLAngleLocOrErr) | |||
650 | return ToLAngleLocOrErr.takeError(); | |||
651 | auto ToRAngleLocOrErr = import(FromRAngleLoc); | |||
652 | if (!ToRAngleLocOrErr) | |||
653 | return ToRAngleLocOrErr.takeError(); | |||
654 | ||||
655 | TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr); | |||
656 | if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo)) | |||
657 | return Err; | |||
658 | Result = ToTAInfo; | |||
659 | return Error::success(); | |||
660 | } | |||
661 | ||||
662 | template <> | |||
663 | Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>( | |||
664 | const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) { | |||
665 | return ImportTemplateArgumentListInfo( | |||
666 | From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result); | |||
667 | } | |||
668 | ||||
669 | template <> | |||
670 | Error ASTNodeImporter::ImportTemplateArgumentListInfo< | |||
671 | ASTTemplateArgumentListInfo>( | |||
672 | const ASTTemplateArgumentListInfo &From, | |||
673 | TemplateArgumentListInfo &Result) { | |||
674 | return ImportTemplateArgumentListInfo( | |||
675 | From.LAngleLoc, From.RAngleLoc, From.arguments(), Result); | |||
676 | } | |||
677 | ||||
678 | Expected<ASTNodeImporter::FunctionTemplateAndArgsTy> | |||
679 | ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( | |||
680 | FunctionDecl *FromFD) { | |||
681 | assert(FromFD->getTemplatedKind() ==((FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization ) ? static_cast<void> (0) : __assert_fail ("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 682, __PRETTY_FUNCTION__)) | |||
682 | FunctionDecl::TK_FunctionTemplateSpecialization)((FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization ) ? static_cast<void> (0) : __assert_fail ("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 682, __PRETTY_FUNCTION__)); | |||
683 | ||||
684 | FunctionTemplateAndArgsTy Result; | |||
685 | ||||
686 | auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); | |||
687 | if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate())) | |||
688 | return std::move(Err); | |||
689 | ||||
690 | // Import template arguments. | |||
691 | auto TemplArgs = FTSInfo->TemplateArguments->asArray(); | |||
692 | if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), | |||
693 | std::get<1>(Result))) | |||
694 | return std::move(Err); | |||
695 | ||||
696 | return Result; | |||
697 | } | |||
698 | ||||
699 | template <> | |||
700 | Expected<TemplateParameterList *> | |||
701 | ASTNodeImporter::import(TemplateParameterList *From) { | |||
702 | SmallVector<NamedDecl *, 4> To(From->size()); | |||
703 | if (Error Err = ImportContainerChecked(*From, To)) | |||
704 | return std::move(Err); | |||
705 | ||||
706 | ExpectedExpr ToRequiresClause = import(From->getRequiresClause()); | |||
707 | if (!ToRequiresClause) | |||
708 | return ToRequiresClause.takeError(); | |||
709 | ||||
710 | auto ToTemplateLocOrErr = import(From->getTemplateLoc()); | |||
711 | if (!ToTemplateLocOrErr) | |||
712 | return ToTemplateLocOrErr.takeError(); | |||
713 | auto ToLAngleLocOrErr = import(From->getLAngleLoc()); | |||
714 | if (!ToLAngleLocOrErr) | |||
715 | return ToLAngleLocOrErr.takeError(); | |||
716 | auto ToRAngleLocOrErr = import(From->getRAngleLoc()); | |||
717 | if (!ToRAngleLocOrErr) | |||
718 | return ToRAngleLocOrErr.takeError(); | |||
719 | ||||
720 | return TemplateParameterList::Create( | |||
721 | Importer.getToContext(), | |||
722 | *ToTemplateLocOrErr, | |||
723 | *ToLAngleLocOrErr, | |||
724 | To, | |||
725 | *ToRAngleLocOrErr, | |||
726 | *ToRequiresClause); | |||
727 | } | |||
728 | ||||
729 | template <> | |||
730 | Expected<TemplateArgument> | |||
731 | ASTNodeImporter::import(const TemplateArgument &From) { | |||
732 | switch (From.getKind()) { | |||
733 | case TemplateArgument::Null: | |||
734 | return TemplateArgument(); | |||
735 | ||||
736 | case TemplateArgument::Type: { | |||
737 | ExpectedType ToTypeOrErr = import(From.getAsType()); | |||
738 | if (!ToTypeOrErr) | |||
739 | return ToTypeOrErr.takeError(); | |||
740 | return TemplateArgument(*ToTypeOrErr); | |||
741 | } | |||
742 | ||||
743 | case TemplateArgument::Integral: { | |||
744 | ExpectedType ToTypeOrErr = import(From.getIntegralType()); | |||
745 | if (!ToTypeOrErr) | |||
746 | return ToTypeOrErr.takeError(); | |||
747 | return TemplateArgument(From, *ToTypeOrErr); | |||
748 | } | |||
749 | ||||
750 | case TemplateArgument::Declaration: { | |||
751 | Expected<ValueDecl *> ToOrErr = import(From.getAsDecl()); | |||
752 | if (!ToOrErr) | |||
753 | return ToOrErr.takeError(); | |||
754 | ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl()); | |||
755 | if (!ToTypeOrErr) | |||
756 | return ToTypeOrErr.takeError(); | |||
757 | return TemplateArgument(*ToOrErr, *ToTypeOrErr); | |||
758 | } | |||
759 | ||||
760 | case TemplateArgument::NullPtr: { | |||
761 | ExpectedType ToTypeOrErr = import(From.getNullPtrType()); | |||
762 | if (!ToTypeOrErr) | |||
763 | return ToTypeOrErr.takeError(); | |||
764 | return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true); | |||
765 | } | |||
766 | ||||
767 | case TemplateArgument::Template: { | |||
768 | Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate()); | |||
769 | if (!ToTemplateOrErr) | |||
770 | return ToTemplateOrErr.takeError(); | |||
771 | ||||
772 | return TemplateArgument(*ToTemplateOrErr); | |||
773 | } | |||
774 | ||||
775 | case TemplateArgument::TemplateExpansion: { | |||
776 | Expected<TemplateName> ToTemplateOrErr = | |||
777 | import(From.getAsTemplateOrTemplatePattern()); | |||
778 | if (!ToTemplateOrErr) | |||
779 | return ToTemplateOrErr.takeError(); | |||
780 | ||||
781 | return TemplateArgument( | |||
782 | *ToTemplateOrErr, From.getNumTemplateExpansions()); | |||
783 | } | |||
784 | ||||
785 | case TemplateArgument::Expression: | |||
786 | if (ExpectedExpr ToExpr = import(From.getAsExpr())) | |||
787 | return TemplateArgument(*ToExpr); | |||
788 | else | |||
789 | return ToExpr.takeError(); | |||
790 | ||||
791 | case TemplateArgument::Pack: { | |||
792 | SmallVector<TemplateArgument, 2> ToPack; | |||
793 | ToPack.reserve(From.pack_size()); | |||
794 | if (Error Err = ImportTemplateArguments( | |||
795 | From.pack_begin(), From.pack_size(), ToPack)) | |||
796 | return std::move(Err); | |||
797 | ||||
798 | return TemplateArgument( | |||
799 | llvm::makeArrayRef(ToPack).copy(Importer.getToContext())); | |||
800 | } | |||
801 | } | |||
802 | ||||
803 | llvm_unreachable("Invalid template argument kind")::llvm::llvm_unreachable_internal("Invalid template argument kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 803); | |||
804 | } | |||
805 | ||||
806 | template <> | |||
807 | Expected<TemplateArgumentLoc> | |||
808 | ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) { | |||
809 | Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument()); | |||
810 | if (!ArgOrErr) | |||
811 | return ArgOrErr.takeError(); | |||
812 | TemplateArgument Arg = *ArgOrErr; | |||
813 | ||||
814 | TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo(); | |||
815 | ||||
816 | TemplateArgumentLocInfo ToInfo; | |||
817 | if (Arg.getKind() == TemplateArgument::Expression) { | |||
818 | ExpectedExpr E = import(FromInfo.getAsExpr()); | |||
819 | if (!E) | |||
820 | return E.takeError(); | |||
821 | ToInfo = TemplateArgumentLocInfo(*E); | |||
822 | } else if (Arg.getKind() == TemplateArgument::Type) { | |||
823 | if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo())) | |||
824 | ToInfo = TemplateArgumentLocInfo(*TSIOrErr); | |||
825 | else | |||
826 | return TSIOrErr.takeError(); | |||
827 | } else { | |||
828 | auto ToTemplateQualifierLocOrErr = | |||
829 | import(FromInfo.getTemplateQualifierLoc()); | |||
830 | if (!ToTemplateQualifierLocOrErr) | |||
831 | return ToTemplateQualifierLocOrErr.takeError(); | |||
832 | auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc()); | |||
833 | if (!ToTemplateNameLocOrErr) | |||
834 | return ToTemplateNameLocOrErr.takeError(); | |||
835 | auto ToTemplateEllipsisLocOrErr = | |||
836 | import(FromInfo.getTemplateEllipsisLoc()); | |||
837 | if (!ToTemplateEllipsisLocOrErr) | |||
838 | return ToTemplateEllipsisLocOrErr.takeError(); | |||
839 | ||||
840 | ToInfo = TemplateArgumentLocInfo( | |||
841 | *ToTemplateQualifierLocOrErr, | |||
842 | *ToTemplateNameLocOrErr, | |||
843 | *ToTemplateEllipsisLocOrErr); | |||
844 | } | |||
845 | ||||
846 | return TemplateArgumentLoc(Arg, ToInfo); | |||
847 | } | |||
848 | ||||
849 | template <> | |||
850 | Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) { | |||
851 | if (DG.isNull()) | |||
852 | return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0); | |||
853 | size_t NumDecls = DG.end() - DG.begin(); | |||
854 | SmallVector<Decl *, 1> ToDecls; | |||
855 | ToDecls.reserve(NumDecls); | |||
856 | for (Decl *FromD : DG) { | |||
857 | if (auto ToDOrErr = import(FromD)) | |||
858 | ToDecls.push_back(*ToDOrErr); | |||
859 | else | |||
860 | return ToDOrErr.takeError(); | |||
861 | } | |||
862 | return DeclGroupRef::Create(Importer.getToContext(), | |||
863 | ToDecls.begin(), | |||
864 | NumDecls); | |||
865 | } | |||
866 | ||||
867 | template <> | |||
868 | Expected<ASTNodeImporter::Designator> | |||
869 | ASTNodeImporter::import(const Designator &D) { | |||
870 | if (D.isFieldDesignator()) { | |||
871 | IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName()); | |||
872 | ||||
873 | ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc()); | |||
874 | if (!ToDotLocOrErr) | |||
875 | return ToDotLocOrErr.takeError(); | |||
876 | ||||
877 | ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc()); | |||
878 | if (!ToFieldLocOrErr) | |||
879 | return ToFieldLocOrErr.takeError(); | |||
880 | ||||
881 | return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr); | |||
882 | } | |||
883 | ||||
884 | ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc()); | |||
885 | if (!ToLBracketLocOrErr) | |||
886 | return ToLBracketLocOrErr.takeError(); | |||
887 | ||||
888 | ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc()); | |||
889 | if (!ToRBracketLocOrErr) | |||
890 | return ToRBracketLocOrErr.takeError(); | |||
891 | ||||
892 | if (D.isArrayDesignator()) | |||
893 | return Designator(D.getFirstExprIndex(), | |||
894 | *ToLBracketLocOrErr, *ToRBracketLocOrErr); | |||
895 | ||||
896 | ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc()); | |||
897 | if (!ToEllipsisLocOrErr) | |||
898 | return ToEllipsisLocOrErr.takeError(); | |||
899 | ||||
900 | assert(D.isArrayRangeDesignator())((D.isArrayRangeDesignator()) ? static_cast<void> (0) : __assert_fail ("D.isArrayRangeDesignator()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 900, __PRETTY_FUNCTION__)); | |||
901 | return Designator( | |||
902 | D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr, | |||
903 | *ToRBracketLocOrErr); | |||
904 | } | |||
905 | ||||
906 | template <> | |||
907 | Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) { | |||
908 | VarDecl *Var = nullptr; | |||
909 | if (From.capturesVariable()) { | |||
910 | if (auto VarOrErr = import(From.getCapturedVar())) | |||
911 | Var = *VarOrErr; | |||
912 | else | |||
913 | return VarOrErr.takeError(); | |||
914 | } | |||
915 | ||||
916 | auto LocationOrErr = import(From.getLocation()); | |||
917 | if (!LocationOrErr) | |||
918 | return LocationOrErr.takeError(); | |||
919 | ||||
920 | SourceLocation EllipsisLoc; | |||
921 | if (From.isPackExpansion()) | |||
922 | if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc())) | |||
923 | return std::move(Err); | |||
924 | ||||
925 | return LambdaCapture( | |||
926 | *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var, | |||
927 | EllipsisLoc); | |||
928 | } | |||
929 | ||||
930 | } // namespace clang | |||
931 | ||||
932 | //---------------------------------------------------------------------------- | |||
933 | // Import Types | |||
934 | //---------------------------------------------------------------------------- | |||
935 | ||||
936 | using namespace clang; | |||
937 | ||||
938 | ExpectedType ASTNodeImporter::VisitType(const Type *T) { | |||
939 | Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node) | |||
940 | << T->getTypeClassName(); | |||
941 | return make_error<ImportError>(ImportError::UnsupportedConstruct); | |||
942 | } | |||
943 | ||||
944 | ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){ | |||
945 | ExpectedType UnderlyingTypeOrErr = import(T->getValueType()); | |||
946 | if (!UnderlyingTypeOrErr) | |||
947 | return UnderlyingTypeOrErr.takeError(); | |||
948 | ||||
949 | return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr); | |||
950 | } | |||
951 | ||||
952 | ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { | |||
953 | switch (T->getKind()) { | |||
954 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
955 | case BuiltinType::Id: \ | |||
956 | return Importer.getToContext().SingletonId; | |||
957 | #include "clang/Basic/OpenCLImageTypes.def" | |||
958 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ | |||
959 | case BuiltinType::Id: \ | |||
960 | return Importer.getToContext().Id##Ty; | |||
961 | #include "clang/Basic/OpenCLExtensionTypes.def" | |||
962 | #define SHARED_SINGLETON_TYPE(Expansion) | |||
963 | #define BUILTIN_TYPE(Id, SingletonId) \ | |||
964 | case BuiltinType::Id: return Importer.getToContext().SingletonId; | |||
965 | #include "clang/AST/BuiltinTypes.def" | |||
966 | ||||
967 | // FIXME: for Char16, Char32, and NullPtr, make sure that the "to" | |||
968 | // context supports C++. | |||
969 | ||||
970 | // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to" | |||
971 | // context supports ObjC. | |||
972 | ||||
973 | case BuiltinType::Char_U: | |||
974 | // The context we're importing from has an unsigned 'char'. If we're | |||
975 | // importing into a context with a signed 'char', translate to | |||
976 | // 'unsigned char' instead. | |||
977 | if (Importer.getToContext().getLangOpts().CharIsSigned) | |||
978 | return Importer.getToContext().UnsignedCharTy; | |||
979 | ||||
980 | return Importer.getToContext().CharTy; | |||
981 | ||||
982 | case BuiltinType::Char_S: | |||
983 | // The context we're importing from has an unsigned 'char'. If we're | |||
984 | // importing into a context with a signed 'char', translate to | |||
985 | // 'unsigned char' instead. | |||
986 | if (!Importer.getToContext().getLangOpts().CharIsSigned) | |||
987 | return Importer.getToContext().SignedCharTy; | |||
988 | ||||
989 | return Importer.getToContext().CharTy; | |||
990 | ||||
991 | case BuiltinType::WChar_S: | |||
992 | case BuiltinType::WChar_U: | |||
993 | // FIXME: If not in C++, shall we translate to the C equivalent of | |||
994 | // wchar_t? | |||
995 | return Importer.getToContext().WCharTy; | |||
996 | } | |||
997 | ||||
998 | llvm_unreachable("Invalid BuiltinType Kind!")::llvm::llvm_unreachable_internal("Invalid BuiltinType Kind!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 998); | |||
999 | } | |||
1000 | ||||
1001 | ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) { | |||
1002 | ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType()); | |||
1003 | if (!ToOriginalTypeOrErr) | |||
1004 | return ToOriginalTypeOrErr.takeError(); | |||
1005 | ||||
1006 | return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr); | |||
1007 | } | |||
1008 | ||||
1009 | ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) { | |||
1010 | ExpectedType ToElementTypeOrErr = import(T->getElementType()); | |||
1011 | if (!ToElementTypeOrErr) | |||
1012 | return ToElementTypeOrErr.takeError(); | |||
1013 | ||||
1014 | return Importer.getToContext().getComplexType(*ToElementTypeOrErr); | |||
1015 | } | |||
1016 | ||||
1017 | ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) { | |||
1018 | ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); | |||
1019 | if (!ToPointeeTypeOrErr) | |||
1020 | return ToPointeeTypeOrErr.takeError(); | |||
1021 | ||||
1022 | return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr); | |||
1023 | } | |||
1024 | ||||
1025 | ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { | |||
1026 | // FIXME: Check for blocks support in "to" context. | |||
1027 | ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); | |||
1028 | if (!ToPointeeTypeOrErr) | |||
1029 | return ToPointeeTypeOrErr.takeError(); | |||
1030 | ||||
1031 | return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr); | |||
1032 | } | |||
1033 | ||||
1034 | ExpectedType | |||
1035 | ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { | |||
1036 | // FIXME: Check for C++ support in "to" context. | |||
1037 | ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); | |||
1038 | if (!ToPointeeTypeOrErr) | |||
1039 | return ToPointeeTypeOrErr.takeError(); | |||
1040 | ||||
1041 | return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr); | |||
1042 | } | |||
1043 | ||||
1044 | ExpectedType | |||
1045 | ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { | |||
1046 | // FIXME: Check for C++0x support in "to" context. | |||
1047 | ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); | |||
1048 | if (!ToPointeeTypeOrErr) | |||
1049 | return ToPointeeTypeOrErr.takeError(); | |||
1050 | ||||
1051 | return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr); | |||
1052 | } | |||
1053 | ||||
1054 | ExpectedType | |||
1055 | ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { | |||
1056 | // FIXME: Check for C++ support in "to" context. | |||
1057 | ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); | |||
1058 | if (!ToPointeeTypeOrErr) | |||
1059 | return ToPointeeTypeOrErr.takeError(); | |||
1060 | ||||
1061 | ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0)); | |||
1062 | if (!ClassTypeOrErr) | |||
1063 | return ClassTypeOrErr.takeError(); | |||
1064 | ||||
1065 | return Importer.getToContext().getMemberPointerType( | |||
1066 | *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr()); | |||
1067 | } | |||
1068 | ||||
1069 | ExpectedType | |||
1070 | ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { | |||
1071 | ExpectedType ToElementTypeOrErr = import(T->getElementType()); | |||
1072 | if (!ToElementTypeOrErr) | |||
1073 | return ToElementTypeOrErr.takeError(); | |||
1074 | ||||
1075 | return Importer.getToContext().getConstantArrayType(*ToElementTypeOrErr, | |||
1076 | T->getSize(), | |||
1077 | T->getSizeModifier(), | |||
1078 | T->getIndexTypeCVRQualifiers()); | |||
1079 | } | |||
1080 | ||||
1081 | ExpectedType | |||
1082 | ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { | |||
1083 | ExpectedType ToElementTypeOrErr = import(T->getElementType()); | |||
1084 | if (!ToElementTypeOrErr) | |||
1085 | return ToElementTypeOrErr.takeError(); | |||
1086 | ||||
1087 | return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr, | |||
1088 | T->getSizeModifier(), | |||
1089 | T->getIndexTypeCVRQualifiers()); | |||
1090 | } | |||
1091 | ||||
1092 | ExpectedType | |||
1093 | ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { | |||
1094 | QualType ToElementType; | |||
1095 | Expr *ToSizeExpr; | |||
1096 | SourceRange ToBracketsRange; | |||
1097 | if (auto Imp = importSeq( | |||
1098 | T->getElementType(), T->getSizeExpr(), T->getBracketsRange())) | |||
1099 | std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp; | |||
1100 | else | |||
1101 | return Imp.takeError(); | |||
1102 | ||||
1103 | return Importer.getToContext().getVariableArrayType( | |||
1104 | ToElementType, ToSizeExpr, T->getSizeModifier(), | |||
1105 | T->getIndexTypeCVRQualifiers(), ToBracketsRange); | |||
1106 | } | |||
1107 | ||||
1108 | ExpectedType ASTNodeImporter::VisitDependentSizedArrayType( | |||
1109 | const DependentSizedArrayType *T) { | |||
1110 | QualType ToElementType; | |||
1111 | Expr *ToSizeExpr; | |||
1112 | SourceRange ToBracketsRange; | |||
1113 | if (auto Imp = importSeq( | |||
1114 | T->getElementType(), T->getSizeExpr(), T->getBracketsRange())) | |||
1115 | std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp; | |||
1116 | else | |||
1117 | return Imp.takeError(); | |||
1118 | // SizeExpr may be null if size is not specified directly. | |||
1119 | // For example, 'int a[]'. | |||
1120 | ||||
1121 | return Importer.getToContext().getDependentSizedArrayType( | |||
1122 | ToElementType, ToSizeExpr, T->getSizeModifier(), | |||
1123 | T->getIndexTypeCVRQualifiers(), ToBracketsRange); | |||
1124 | } | |||
1125 | ||||
1126 | ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) { | |||
1127 | ExpectedType ToElementTypeOrErr = import(T->getElementType()); | |||
1128 | if (!ToElementTypeOrErr) | |||
1129 | return ToElementTypeOrErr.takeError(); | |||
1130 | ||||
1131 | return Importer.getToContext().getVectorType(*ToElementTypeOrErr, | |||
1132 | T->getNumElements(), | |||
1133 | T->getVectorKind()); | |||
1134 | } | |||
1135 | ||||
1136 | ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { | |||
1137 | ExpectedType ToElementTypeOrErr = import(T->getElementType()); | |||
1138 | if (!ToElementTypeOrErr) | |||
1139 | return ToElementTypeOrErr.takeError(); | |||
1140 | ||||
1141 | return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr, | |||
1142 | T->getNumElements()); | |||
1143 | } | |||
1144 | ||||
1145 | ExpectedType | |||
1146 | ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { | |||
1147 | // FIXME: What happens if we're importing a function without a prototype | |||
1148 | // into C++? Should we make it variadic? | |||
1149 | ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); | |||
1150 | if (!ToReturnTypeOrErr) | |||
1151 | return ToReturnTypeOrErr.takeError(); | |||
1152 | ||||
1153 | return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr, | |||
1154 | T->getExtInfo()); | |||
1155 | } | |||
1156 | ||||
1157 | ExpectedType | |||
1158 | ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { | |||
1159 | ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); | |||
1160 | if (!ToReturnTypeOrErr) | |||
1161 | return ToReturnTypeOrErr.takeError(); | |||
1162 | ||||
1163 | // Import argument types | |||
1164 | SmallVector<QualType, 4> ArgTypes; | |||
1165 | for (const auto &A : T->param_types()) { | |||
1166 | ExpectedType TyOrErr = import(A); | |||
1167 | if (!TyOrErr) | |||
1168 | return TyOrErr.takeError(); | |||
1169 | ArgTypes.push_back(*TyOrErr); | |||
1170 | } | |||
1171 | ||||
1172 | // Import exception types | |||
1173 | SmallVector<QualType, 4> ExceptionTypes; | |||
1174 | for (const auto &E : T->exceptions()) { | |||
1175 | ExpectedType TyOrErr = import(E); | |||
1176 | if (!TyOrErr) | |||
1177 | return TyOrErr.takeError(); | |||
1178 | ExceptionTypes.push_back(*TyOrErr); | |||
1179 | } | |||
1180 | ||||
1181 | FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo(); | |||
1182 | FunctionProtoType::ExtProtoInfo ToEPI; | |||
1183 | ||||
1184 | auto Imp = importSeq( | |||
1185 | FromEPI.ExceptionSpec.NoexceptExpr, | |||
1186 | FromEPI.ExceptionSpec.SourceDecl, | |||
1187 | FromEPI.ExceptionSpec.SourceTemplate); | |||
1188 | if (!Imp) | |||
1189 | return Imp.takeError(); | |||
1190 | ||||
1191 | ToEPI.ExtInfo = FromEPI.ExtInfo; | |||
1192 | ToEPI.Variadic = FromEPI.Variadic; | |||
1193 | ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn; | |||
1194 | ToEPI.TypeQuals = FromEPI.TypeQuals; | |||
1195 | ToEPI.RefQualifier = FromEPI.RefQualifier; | |||
1196 | ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type; | |||
1197 | ToEPI.ExceptionSpec.Exceptions = ExceptionTypes; | |||
1198 | std::tie( | |||
1199 | ToEPI.ExceptionSpec.NoexceptExpr, | |||
1200 | ToEPI.ExceptionSpec.SourceDecl, | |||
1201 | ToEPI.ExceptionSpec.SourceTemplate) = *Imp; | |||
1202 | ||||
1203 | return Importer.getToContext().getFunctionType( | |||
1204 | *ToReturnTypeOrErr, ArgTypes, ToEPI); | |||
1205 | } | |||
1206 | ||||
1207 | ExpectedType ASTNodeImporter::VisitUnresolvedUsingType( | |||
1208 | const UnresolvedUsingType *T) { | |||
1209 | UnresolvedUsingTypenameDecl *ToD; | |||
1210 | Decl *ToPrevD; | |||
1211 | if (auto Imp = importSeq(T->getDecl(), T->getDecl()->getPreviousDecl())) | |||
1212 | std::tie(ToD, ToPrevD) = *Imp; | |||
1213 | else | |||
1214 | return Imp.takeError(); | |||
1215 | ||||
1216 | return Importer.getToContext().getTypeDeclType( | |||
1217 | ToD, cast_or_null<TypeDecl>(ToPrevD)); | |||
1218 | } | |||
1219 | ||||
1220 | ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) { | |||
1221 | ExpectedType ToInnerTypeOrErr = import(T->getInnerType()); | |||
1222 | if (!ToInnerTypeOrErr) | |||
1223 | return ToInnerTypeOrErr.takeError(); | |||
1224 | ||||
1225 | return Importer.getToContext().getParenType(*ToInnerTypeOrErr); | |||
1226 | } | |||
1227 | ||||
1228 | ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { | |||
1229 | Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl()); | |||
1230 | if (!ToDeclOrErr) | |||
1231 | return ToDeclOrErr.takeError(); | |||
1232 | ||||
1233 | return Importer.getToContext().getTypeDeclType(*ToDeclOrErr); | |||
1234 | } | |||
1235 | ||||
1236 | ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { | |||
1237 | ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); | |||
1238 | if (!ToExprOrErr) | |||
1239 | return ToExprOrErr.takeError(); | |||
1240 | ||||
1241 | return Importer.getToContext().getTypeOfExprType(*ToExprOrErr); | |||
1242 | } | |||
1243 | ||||
1244 | ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { | |||
1245 | ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); | |||
1246 | if (!ToUnderlyingTypeOrErr) | |||
1247 | return ToUnderlyingTypeOrErr.takeError(); | |||
1248 | ||||
1249 | return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr); | |||
1250 | } | |||
1251 | ||||
1252 | ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { | |||
1253 | // FIXME: Make sure that the "to" context supports C++0x! | |||
1254 | ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); | |||
1255 | if (!ToExprOrErr) | |||
1256 | return ToExprOrErr.takeError(); | |||
1257 | ||||
1258 | ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); | |||
1259 | if (!ToUnderlyingTypeOrErr) | |||
1260 | return ToUnderlyingTypeOrErr.takeError(); | |||
1261 | ||||
1262 | return Importer.getToContext().getDecltypeType( | |||
1263 | *ToExprOrErr, *ToUnderlyingTypeOrErr); | |||
1264 | } | |||
1265 | ||||
1266 | ExpectedType | |||
1267 | ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) { | |||
1268 | ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); | |||
1269 | if (!ToBaseTypeOrErr) | |||
1270 | return ToBaseTypeOrErr.takeError(); | |||
1271 | ||||
1272 | ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); | |||
1273 | if (!ToUnderlyingTypeOrErr) | |||
1274 | return ToUnderlyingTypeOrErr.takeError(); | |||
1275 | ||||
1276 | return Importer.getToContext().getUnaryTransformType( | |||
1277 | *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind()); | |||
1278 | } | |||
1279 | ||||
1280 | ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) { | |||
1281 | // FIXME: Make sure that the "to" context supports C++11! | |||
1282 | ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType()); | |||
1283 | if (!ToDeducedTypeOrErr) | |||
1284 | return ToDeducedTypeOrErr.takeError(); | |||
1285 | ||||
1286 | return Importer.getToContext().getAutoType(*ToDeducedTypeOrErr, | |||
1287 | T->getKeyword(), | |||
1288 | /*IsDependent*/false); | |||
1289 | } | |||
1290 | ||||
1291 | ExpectedType ASTNodeImporter::VisitInjectedClassNameType( | |||
1292 | const InjectedClassNameType *T) { | |||
1293 | Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl()); | |||
1294 | if (!ToDeclOrErr) | |||
1295 | return ToDeclOrErr.takeError(); | |||
1296 | ||||
1297 | ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType()); | |||
1298 | if (!ToInjTypeOrErr) | |||
1299 | return ToInjTypeOrErr.takeError(); | |||
1300 | ||||
1301 | // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading | |||
1302 | // See comments in InjectedClassNameType definition for details | |||
1303 | // return Importer.getToContext().getInjectedClassNameType(D, InjType); | |||
1304 | enum { | |||
1305 | TypeAlignmentInBits = 4, | |||
1306 | TypeAlignment = 1 << TypeAlignmentInBits | |||
1307 | }; | |||
1308 | ||||
1309 | return QualType(new (Importer.getToContext(), TypeAlignment) | |||
1310 | InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0); | |||
1311 | } | |||
1312 | ||||
1313 | ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) { | |||
1314 | Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl()); | |||
1315 | if (!ToDeclOrErr) | |||
1316 | return ToDeclOrErr.takeError(); | |||
1317 | ||||
1318 | return Importer.getToContext().getTagDeclType(*ToDeclOrErr); | |||
1319 | } | |||
1320 | ||||
1321 | ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) { | |||
1322 | Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl()); | |||
1323 | if (!ToDeclOrErr) | |||
1324 | return ToDeclOrErr.takeError(); | |||
1325 | ||||
1326 | return Importer.getToContext().getTagDeclType(*ToDeclOrErr); | |||
1327 | } | |||
1328 | ||||
1329 | ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) { | |||
1330 | ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType()); | |||
1331 | if (!ToModifiedTypeOrErr) | |||
1332 | return ToModifiedTypeOrErr.takeError(); | |||
1333 | ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType()); | |||
1334 | if (!ToEquivalentTypeOrErr) | |||
1335 | return ToEquivalentTypeOrErr.takeError(); | |||
1336 | ||||
1337 | return Importer.getToContext().getAttributedType(T->getAttrKind(), | |||
1338 | *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr); | |||
1339 | } | |||
1340 | ||||
1341 | ExpectedType ASTNodeImporter::VisitTemplateTypeParmType( | |||
1342 | const TemplateTypeParmType *T) { | |||
1343 | Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl()); | |||
1344 | if (!ToDeclOrErr) | |||
1345 | return ToDeclOrErr.takeError(); | |||
1346 | ||||
1347 | return Importer.getToContext().getTemplateTypeParmType( | |||
1348 | T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr); | |||
1349 | } | |||
1350 | ||||
1351 | ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType( | |||
1352 | const SubstTemplateTypeParmType *T) { | |||
1353 | ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0)); | |||
1354 | if (!ReplacedOrErr) | |||
1355 | return ReplacedOrErr.takeError(); | |||
1356 | const TemplateTypeParmType *Replaced = | |||
1357 | cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr()); | |||
1358 | ||||
1359 | ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType()); | |||
1360 | if (!ToReplacementTypeOrErr) | |||
1361 | return ToReplacementTypeOrErr.takeError(); | |||
1362 | ||||
1363 | return Importer.getToContext().getSubstTemplateTypeParmType( | |||
1364 | Replaced, (*ToReplacementTypeOrErr).getCanonicalType()); | |||
1365 | } | |||
1366 | ||||
1367 | ExpectedType ASTNodeImporter::VisitTemplateSpecializationType( | |||
1368 | const TemplateSpecializationType *T) { | |||
1369 | auto ToTemplateOrErr = import(T->getTemplateName()); | |||
1370 | if (!ToTemplateOrErr) | |||
1371 | return ToTemplateOrErr.takeError(); | |||
1372 | ||||
1373 | SmallVector<TemplateArgument, 2> ToTemplateArgs; | |||
1374 | if (Error Err = ImportTemplateArguments( | |||
1375 | T->getArgs(), T->getNumArgs(), ToTemplateArgs)) | |||
1376 | return std::move(Err); | |||
1377 | ||||
1378 | QualType ToCanonType; | |||
1379 | if (!QualType(T, 0).isCanonical()) { | |||
1380 | QualType FromCanonType | |||
1381 | = Importer.getFromContext().getCanonicalType(QualType(T, 0)); | |||
1382 | if (ExpectedType TyOrErr = import(FromCanonType)) | |||
1383 | ToCanonType = *TyOrErr; | |||
1384 | else | |||
1385 | return TyOrErr.takeError(); | |||
1386 | } | |||
1387 | return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr, | |||
1388 | ToTemplateArgs, | |||
1389 | ToCanonType); | |||
1390 | } | |||
1391 | ||||
1392 | ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) { | |||
1393 | // Note: the qualifier in an ElaboratedType is optional. | |||
1394 | auto ToQualifierOrErr = import(T->getQualifier()); | |||
1395 | if (!ToQualifierOrErr) | |||
1396 | return ToQualifierOrErr.takeError(); | |||
1397 | ||||
1398 | ExpectedType ToNamedTypeOrErr = import(T->getNamedType()); | |||
1399 | if (!ToNamedTypeOrErr) | |||
1400 | return ToNamedTypeOrErr.takeError(); | |||
1401 | ||||
1402 | Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl()); | |||
1403 | if (!ToOwnedTagDeclOrErr) | |||
1404 | return ToOwnedTagDeclOrErr.takeError(); | |||
1405 | ||||
1406 | return Importer.getToContext().getElaboratedType(T->getKeyword(), | |||
1407 | *ToQualifierOrErr, | |||
1408 | *ToNamedTypeOrErr, | |||
1409 | *ToOwnedTagDeclOrErr); | |||
1410 | } | |||
1411 | ||||
1412 | ExpectedType | |||
1413 | ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) { | |||
1414 | ExpectedType ToPatternOrErr = import(T->getPattern()); | |||
1415 | if (!ToPatternOrErr) | |||
1416 | return ToPatternOrErr.takeError(); | |||
1417 | ||||
1418 | return Importer.getToContext().getPackExpansionType(*ToPatternOrErr, | |||
1419 | T->getNumExpansions()); | |||
1420 | } | |||
1421 | ||||
1422 | ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType( | |||
1423 | const DependentTemplateSpecializationType *T) { | |||
1424 | auto ToQualifierOrErr = import(T->getQualifier()); | |||
1425 | if (!ToQualifierOrErr) | |||
1426 | return ToQualifierOrErr.takeError(); | |||
1427 | ||||
1428 | IdentifierInfo *ToName = Importer.Import(T->getIdentifier()); | |||
1429 | ||||
1430 | SmallVector<TemplateArgument, 2> ToPack; | |||
1431 | ToPack.reserve(T->getNumArgs()); | |||
1432 | if (Error Err = ImportTemplateArguments( | |||
1433 | T->getArgs(), T->getNumArgs(), ToPack)) | |||
1434 | return std::move(Err); | |||
1435 | ||||
1436 | return Importer.getToContext().getDependentTemplateSpecializationType( | |||
1437 | T->getKeyword(), *ToQualifierOrErr, ToName, ToPack); | |||
1438 | } | |||
1439 | ||||
1440 | ExpectedType | |||
1441 | ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) { | |||
1442 | auto ToQualifierOrErr = import(T->getQualifier()); | |||
1443 | if (!ToQualifierOrErr) | |||
1444 | return ToQualifierOrErr.takeError(); | |||
1445 | ||||
1446 | IdentifierInfo *Name = Importer.Import(T->getIdentifier()); | |||
1447 | ||||
1448 | QualType Canon; | |||
1449 | if (T != T->getCanonicalTypeInternal().getTypePtr()) { | |||
1450 | if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal())) | |||
1451 | Canon = (*TyOrErr).getCanonicalType(); | |||
1452 | else | |||
1453 | return TyOrErr.takeError(); | |||
1454 | } | |||
1455 | ||||
1456 | return Importer.getToContext().getDependentNameType(T->getKeyword(), | |||
1457 | *ToQualifierOrErr, | |||
1458 | Name, Canon); | |||
1459 | } | |||
1460 | ||||
1461 | ExpectedType | |||
1462 | ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { | |||
1463 | Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl()); | |||
1464 | if (!ToDeclOrErr) | |||
1465 | return ToDeclOrErr.takeError(); | |||
1466 | ||||
1467 | return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr); | |||
1468 | } | |||
1469 | ||||
1470 | ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) { | |||
1471 | ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); | |||
1472 | if (!ToBaseTypeOrErr) | |||
1473 | return ToBaseTypeOrErr.takeError(); | |||
1474 | ||||
1475 | SmallVector<QualType, 4> TypeArgs; | |||
1476 | for (auto TypeArg : T->getTypeArgsAsWritten()) { | |||
1477 | if (ExpectedType TyOrErr = import(TypeArg)) | |||
1478 | TypeArgs.push_back(*TyOrErr); | |||
1479 | else | |||
1480 | return TyOrErr.takeError(); | |||
1481 | } | |||
1482 | ||||
1483 | SmallVector<ObjCProtocolDecl *, 4> Protocols; | |||
1484 | for (auto *P : T->quals()) { | |||
1485 | if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P)) | |||
1486 | Protocols.push_back(*ProtocolOrErr); | |||
1487 | else | |||
1488 | return ProtocolOrErr.takeError(); | |||
1489 | ||||
1490 | } | |||
1491 | ||||
1492 | return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs, | |||
1493 | Protocols, | |||
1494 | T->isKindOfTypeAsWritten()); | |||
1495 | } | |||
1496 | ||||
1497 | ExpectedType | |||
1498 | ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { | |||
1499 | ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); | |||
1500 | if (!ToPointeeTypeOrErr) | |||
1501 | return ToPointeeTypeOrErr.takeError(); | |||
1502 | ||||
1503 | return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr); | |||
1504 | } | |||
1505 | ||||
1506 | //---------------------------------------------------------------------------- | |||
1507 | // Import Declarations | |||
1508 | //---------------------------------------------------------------------------- | |||
1509 | Error ASTNodeImporter::ImportDeclParts( | |||
1510 | NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, | |||
1511 | DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) { | |||
1512 | // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop. | |||
1513 | // example: int struct_in_proto(struct data_t{int a;int b;} *d); | |||
1514 | DeclContext *OrigDC = D->getDeclContext(); | |||
1515 | FunctionDecl *FunDecl; | |||
1516 | if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) && | |||
1517 | FunDecl->hasBody()) { | |||
1518 | auto getLeafPointeeType = [](const Type *T) { | |||
1519 | while (T->isPointerType() || T->isArrayType()) { | |||
1520 | T = T->getPointeeOrArrayElementType(); | |||
1521 | } | |||
1522 | return T; | |||
1523 | }; | |||
1524 | for (const ParmVarDecl *P : FunDecl->parameters()) { | |||
1525 | const Type *LeafT = | |||
1526 | getLeafPointeeType(P->getType().getCanonicalType().getTypePtr()); | |||
1527 | auto *RT = dyn_cast<RecordType>(LeafT); | |||
1528 | if (RT && RT->getDecl() == D) { | |||
1529 | Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) | |||
1530 | << D->getDeclKindName(); | |||
1531 | return make_error<ImportError>(ImportError::UnsupportedConstruct); | |||
1532 | } | |||
1533 | } | |||
1534 | } | |||
1535 | ||||
1536 | // Import the context of this declaration. | |||
1537 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
1538 | return Err; | |||
1539 | ||||
1540 | // Import the name of this declaration. | |||
1541 | if (Error Err = importInto(Name, D->getDeclName())) | |||
1542 | return Err; | |||
1543 | ||||
1544 | // Import the location of this declaration. | |||
1545 | if (Error Err = importInto(Loc, D->getLocation())) | |||
1546 | return Err; | |||
1547 | ||||
1548 | ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); | |||
1549 | if (ToD) | |||
1550 | if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD)) | |||
1551 | return Err; | |||
1552 | ||||
1553 | return Error::success(); | |||
1554 | } | |||
1555 | ||||
1556 | Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) { | |||
1557 | if (!FromD) | |||
1558 | return Error::success(); | |||
1559 | ||||
1560 | if (!ToD) | |||
1561 | if (Error Err = importInto(ToD, FromD)) | |||
1562 | return Err; | |||
1563 | ||||
1564 | if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) { | |||
1565 | if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) { | |||
1566 | if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && | |||
1567 | !ToRecord->getDefinition()) { | |||
1568 | if (Error Err = ImportDefinition(FromRecord, ToRecord)) | |||
1569 | return Err; | |||
1570 | } | |||
1571 | } | |||
1572 | return Error::success(); | |||
1573 | } | |||
1574 | ||||
1575 | if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) { | |||
1576 | if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) { | |||
1577 | if (FromEnum->getDefinition() && !ToEnum->getDefinition()) { | |||
1578 | if (Error Err = ImportDefinition(FromEnum, ToEnum)) | |||
1579 | return Err; | |||
1580 | } | |||
1581 | } | |||
1582 | return Error::success(); | |||
1583 | } | |||
1584 | ||||
1585 | return Error::success(); | |||
1586 | } | |||
1587 | ||||
1588 | Error | |||
1589 | ASTNodeImporter::ImportDeclarationNameLoc( | |||
1590 | const DeclarationNameInfo &From, DeclarationNameInfo& To) { | |||
1591 | // NOTE: To.Name and To.Loc are already imported. | |||
1592 | // We only have to import To.LocInfo. | |||
1593 | switch (To.getName().getNameKind()) { | |||
1594 | case DeclarationName::Identifier: | |||
1595 | case DeclarationName::ObjCZeroArgSelector: | |||
1596 | case DeclarationName::ObjCOneArgSelector: | |||
1597 | case DeclarationName::ObjCMultiArgSelector: | |||
1598 | case DeclarationName::CXXUsingDirective: | |||
1599 | case DeclarationName::CXXDeductionGuideName: | |||
1600 | return Error::success(); | |||
1601 | ||||
1602 | case DeclarationName::CXXOperatorName: { | |||
1603 | if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange())) | |||
1604 | To.setCXXOperatorNameRange(*ToRangeOrErr); | |||
1605 | else | |||
1606 | return ToRangeOrErr.takeError(); | |||
1607 | return Error::success(); | |||
1608 | } | |||
1609 | case DeclarationName::CXXLiteralOperatorName: { | |||
1610 | if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc())) | |||
1611 | To.setCXXLiteralOperatorNameLoc(*LocOrErr); | |||
1612 | else | |||
1613 | return LocOrErr.takeError(); | |||
1614 | return Error::success(); | |||
1615 | } | |||
1616 | case DeclarationName::CXXConstructorName: | |||
1617 | case DeclarationName::CXXDestructorName: | |||
1618 | case DeclarationName::CXXConversionFunctionName: { | |||
1619 | if (auto ToTInfoOrErr = import(From.getNamedTypeInfo())) | |||
1620 | To.setNamedTypeInfo(*ToTInfoOrErr); | |||
1621 | else | |||
1622 | return ToTInfoOrErr.takeError(); | |||
1623 | return Error::success(); | |||
1624 | } | |||
1625 | } | |||
1626 | llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 1626); | |||
1627 | } | |||
1628 | ||||
1629 | Error | |||
1630 | ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { | |||
1631 | if (Importer.isMinimalImport() && !ForceImport) { | |||
1632 | auto ToDCOrErr = Importer.ImportContext(FromDC); | |||
1633 | return ToDCOrErr.takeError(); | |||
1634 | } | |||
1635 | llvm::SmallVector<Decl *, 8> ImportedDecls; | |||
1636 | for (auto *From : FromDC->decls()) { | |||
1637 | ExpectedDecl ImportedOrErr = import(From); | |||
1638 | if (!ImportedOrErr) | |||
1639 | // Ignore the error, continue with next Decl. | |||
1640 | // FIXME: Handle this case somehow better. | |||
1641 | consumeError(ImportedOrErr.takeError()); | |||
1642 | } | |||
1643 | ||||
1644 | return Error::success(); | |||
1645 | } | |||
1646 | ||||
1647 | Error ASTNodeImporter::ImportDeclContext( | |||
1648 | Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) { | |||
1649 | auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext()); | |||
1650 | if (!ToDCOrErr) | |||
1651 | return ToDCOrErr.takeError(); | |||
1652 | ToDC = *ToDCOrErr; | |||
1653 | ||||
1654 | if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) { | |||
1655 | auto ToLexicalDCOrErr = Importer.ImportContext( | |||
1656 | FromD->getLexicalDeclContext()); | |||
1657 | if (!ToLexicalDCOrErr) | |||
1658 | return ToLexicalDCOrErr.takeError(); | |||
1659 | ToLexicalDC = *ToLexicalDCOrErr; | |||
1660 | } else | |||
1661 | ToLexicalDC = ToDC; | |||
1662 | ||||
1663 | return Error::success(); | |||
1664 | } | |||
1665 | ||||
1666 | Error ASTNodeImporter::ImportImplicitMethods( | |||
1667 | const CXXRecordDecl *From, CXXRecordDecl *To) { | |||
1668 | assert(From->isCompleteDefinition() && To->getDefinition() == To &&((From->isCompleteDefinition() && To->getDefinition () == To && "Import implicit methods to or from non-definition" ) ? static_cast<void> (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 1669, __PRETTY_FUNCTION__)) | |||
1669 | "Import implicit methods to or from non-definition")((From->isCompleteDefinition() && To->getDefinition () == To && "Import implicit methods to or from non-definition" ) ? static_cast<void> (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 1669, __PRETTY_FUNCTION__)); | |||
1670 | ||||
1671 | for (CXXMethodDecl *FromM : From->methods()) | |||
1672 | if (FromM->isImplicit()) { | |||
1673 | Expected<CXXMethodDecl *> ToMOrErr = import(FromM); | |||
1674 | if (!ToMOrErr) | |||
1675 | return ToMOrErr.takeError(); | |||
1676 | } | |||
1677 | ||||
1678 | return Error::success(); | |||
1679 | } | |||
1680 | ||||
1681 | static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To, | |||
1682 | ASTImporter &Importer) { | |||
1683 | if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) { | |||
1684 | if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef)) | |||
1685 | To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr)); | |||
1686 | else | |||
1687 | return ToTypedefOrErr.takeError(); | |||
1688 | } | |||
1689 | return Error::success(); | |||
1690 | } | |||
1691 | ||||
1692 | Error ASTNodeImporter::ImportDefinition( | |||
1693 | RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { | |||
1694 | if (To->getDefinition() || To->isBeingDefined()) { | |||
1695 | if (Kind == IDK_Everything) | |||
1696 | return ImportDeclContext(From, /*ForceImport=*/true); | |||
1697 | ||||
1698 | return Error::success(); | |||
1699 | } | |||
1700 | ||||
1701 | To->startDefinition(); | |||
1702 | ||||
1703 | if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) | |||
1704 | return Err; | |||
1705 | ||||
1706 | // Add base classes. | |||
1707 | auto *ToCXX = dyn_cast<CXXRecordDecl>(To); | |||
1708 | auto *FromCXX = dyn_cast<CXXRecordDecl>(From); | |||
1709 | if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) { | |||
1710 | ||||
1711 | struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data(); | |||
1712 | struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data(); | |||
1713 | ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor; | |||
1714 | ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers; | |||
1715 | ToData.Aggregate = FromData.Aggregate; | |||
1716 | ToData.PlainOldData = FromData.PlainOldData; | |||
1717 | ToData.Empty = FromData.Empty; | |||
1718 | ToData.Polymorphic = FromData.Polymorphic; | |||
1719 | ToData.Abstract = FromData.Abstract; | |||
1720 | ToData.IsStandardLayout = FromData.IsStandardLayout; | |||
1721 | ToData.IsCXX11StandardLayout = FromData.IsCXX11StandardLayout; | |||
1722 | ToData.HasBasesWithFields = FromData.HasBasesWithFields; | |||
1723 | ToData.HasBasesWithNonStaticDataMembers = | |||
1724 | FromData.HasBasesWithNonStaticDataMembers; | |||
1725 | ToData.HasPrivateFields = FromData.HasPrivateFields; | |||
1726 | ToData.HasProtectedFields = FromData.HasProtectedFields; | |||
1727 | ToData.HasPublicFields = FromData.HasPublicFields; | |||
1728 | ToData.HasMutableFields = FromData.HasMutableFields; | |||
1729 | ToData.HasVariantMembers = FromData.HasVariantMembers; | |||
1730 | ToData.HasOnlyCMembers = FromData.HasOnlyCMembers; | |||
1731 | ToData.HasInClassInitializer = FromData.HasInClassInitializer; | |||
1732 | ToData.HasUninitializedReferenceMember | |||
1733 | = FromData.HasUninitializedReferenceMember; | |||
1734 | ToData.HasUninitializedFields = FromData.HasUninitializedFields; | |||
1735 | ToData.HasInheritedConstructor = FromData.HasInheritedConstructor; | |||
1736 | ToData.HasInheritedAssignment = FromData.HasInheritedAssignment; | |||
1737 | ToData.NeedOverloadResolutionForCopyConstructor | |||
1738 | = FromData.NeedOverloadResolutionForCopyConstructor; | |||
1739 | ToData.NeedOverloadResolutionForMoveConstructor | |||
1740 | = FromData.NeedOverloadResolutionForMoveConstructor; | |||
1741 | ToData.NeedOverloadResolutionForMoveAssignment | |||
1742 | = FromData.NeedOverloadResolutionForMoveAssignment; | |||
1743 | ToData.NeedOverloadResolutionForDestructor | |||
1744 | = FromData.NeedOverloadResolutionForDestructor; | |||
1745 | ToData.DefaultedCopyConstructorIsDeleted | |||
1746 | = FromData.DefaultedCopyConstructorIsDeleted; | |||
1747 | ToData.DefaultedMoveConstructorIsDeleted | |||
1748 | = FromData.DefaultedMoveConstructorIsDeleted; | |||
1749 | ToData.DefaultedMoveAssignmentIsDeleted | |||
1750 | = FromData.DefaultedMoveAssignmentIsDeleted; | |||
1751 | ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted; | |||
1752 | ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers; | |||
1753 | ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor; | |||
1754 | ToData.HasConstexprNonCopyMoveConstructor | |||
1755 | = FromData.HasConstexprNonCopyMoveConstructor; | |||
1756 | ToData.HasDefaultedDefaultConstructor | |||
1757 | = FromData.HasDefaultedDefaultConstructor; | |||
1758 | ToData.DefaultedDefaultConstructorIsConstexpr | |||
1759 | = FromData.DefaultedDefaultConstructorIsConstexpr; | |||
1760 | ToData.HasConstexprDefaultConstructor | |||
1761 | = FromData.HasConstexprDefaultConstructor; | |||
1762 | ToData.HasNonLiteralTypeFieldsOrBases | |||
1763 | = FromData.HasNonLiteralTypeFieldsOrBases; | |||
1764 | // ComputedVisibleConversions not imported. | |||
1765 | ToData.UserProvidedDefaultConstructor | |||
1766 | = FromData.UserProvidedDefaultConstructor; | |||
1767 | ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers; | |||
1768 | ToData.ImplicitCopyConstructorCanHaveConstParamForVBase | |||
1769 | = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase; | |||
1770 | ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase | |||
1771 | = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase; | |||
1772 | ToData.ImplicitCopyAssignmentHasConstParam | |||
1773 | = FromData.ImplicitCopyAssignmentHasConstParam; | |||
1774 | ToData.HasDeclaredCopyConstructorWithConstParam | |||
1775 | = FromData.HasDeclaredCopyConstructorWithConstParam; | |||
1776 | ToData.HasDeclaredCopyAssignmentWithConstParam | |||
1777 | = FromData.HasDeclaredCopyAssignmentWithConstParam; | |||
1778 | ||||
1779 | // Copy over the data stored in RecordDeclBits | |||
1780 | ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions()); | |||
1781 | ||||
1782 | SmallVector<CXXBaseSpecifier *, 4> Bases; | |||
1783 | for (const auto &Base1 : FromCXX->bases()) { | |||
1784 | ExpectedType TyOrErr = import(Base1.getType()); | |||
1785 | if (!TyOrErr) | |||
1786 | return TyOrErr.takeError(); | |||
1787 | ||||
1788 | SourceLocation EllipsisLoc; | |||
1789 | if (Base1.isPackExpansion()) { | |||
1790 | if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc())) | |||
1791 | EllipsisLoc = *LocOrErr; | |||
1792 | else | |||
1793 | return LocOrErr.takeError(); | |||
1794 | } | |||
1795 | ||||
1796 | // Ensure that we have a definition for the base. | |||
1797 | if (Error Err = | |||
1798 | ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl())) | |||
1799 | return Err; | |||
1800 | ||||
1801 | auto RangeOrErr = import(Base1.getSourceRange()); | |||
1802 | if (!RangeOrErr) | |||
1803 | return RangeOrErr.takeError(); | |||
1804 | ||||
1805 | auto TSIOrErr = import(Base1.getTypeSourceInfo()); | |||
1806 | if (!TSIOrErr) | |||
1807 | return TSIOrErr.takeError(); | |||
1808 | ||||
1809 | Bases.push_back( | |||
1810 | new (Importer.getToContext()) CXXBaseSpecifier( | |||
1811 | *RangeOrErr, | |||
1812 | Base1.isVirtual(), | |||
1813 | Base1.isBaseOfClass(), | |||
1814 | Base1.getAccessSpecifierAsWritten(), | |||
1815 | *TSIOrErr, | |||
1816 | EllipsisLoc)); | |||
1817 | } | |||
1818 | if (!Bases.empty()) | |||
1819 | ToCXX->setBases(Bases.data(), Bases.size()); | |||
1820 | } | |||
1821 | ||||
1822 | if (shouldForceImportDeclContext(Kind)) | |||
1823 | if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) | |||
1824 | return Err; | |||
1825 | ||||
1826 | To->completeDefinition(); | |||
1827 | return Error::success(); | |||
1828 | } | |||
1829 | ||||
1830 | Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) { | |||
1831 | if (To->getAnyInitializer()) | |||
1832 | return Error::success(); | |||
1833 | ||||
1834 | Expr *FromInit = From->getInit(); | |||
1835 | if (!FromInit) | |||
1836 | return Error::success(); | |||
1837 | ||||
1838 | ExpectedExpr ToInitOrErr = import(FromInit); | |||
1839 | if (!ToInitOrErr) | |||
1840 | return ToInitOrErr.takeError(); | |||
1841 | ||||
1842 | To->setInit(*ToInitOrErr); | |||
1843 | if (From->isInitKnownICE()) { | |||
1844 | EvaluatedStmt *Eval = To->ensureEvaluatedStmt(); | |||
1845 | Eval->CheckedICE = true; | |||
1846 | Eval->IsICE = From->isInitICE(); | |||
1847 | } | |||
1848 | ||||
1849 | // FIXME: Other bits to merge? | |||
1850 | return Error::success(); | |||
1851 | } | |||
1852 | ||||
1853 | Error ASTNodeImporter::ImportDefinition( | |||
1854 | EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { | |||
1855 | if (To->getDefinition() || To->isBeingDefined()) { | |||
1856 | if (Kind == IDK_Everything) | |||
1857 | return ImportDeclContext(From, /*ForceImport=*/true); | |||
1858 | return Error::success(); | |||
1859 | } | |||
1860 | ||||
1861 | To->startDefinition(); | |||
1862 | ||||
1863 | if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) | |||
1864 | return Err; | |||
1865 | ||||
1866 | ExpectedType ToTypeOrErr = | |||
1867 | import(Importer.getFromContext().getTypeDeclType(From)); | |||
1868 | if (!ToTypeOrErr) | |||
1869 | return ToTypeOrErr.takeError(); | |||
1870 | ||||
1871 | ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType()); | |||
1872 | if (!ToPromotionTypeOrErr) | |||
1873 | return ToPromotionTypeOrErr.takeError(); | |||
1874 | ||||
1875 | if (shouldForceImportDeclContext(Kind)) | |||
1876 | if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) | |||
1877 | return Err; | |||
1878 | ||||
1879 | // FIXME: we might need to merge the number of positive or negative bits | |||
1880 | // if the enumerator lists don't match. | |||
1881 | To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr, | |||
1882 | From->getNumPositiveBits(), | |||
1883 | From->getNumNegativeBits()); | |||
1884 | return Error::success(); | |||
1885 | } | |||
1886 | ||||
1887 | Error ASTNodeImporter::ImportTemplateArguments( | |||
1888 | const TemplateArgument *FromArgs, unsigned NumFromArgs, | |||
1889 | SmallVectorImpl<TemplateArgument> &ToArgs) { | |||
1890 | for (unsigned I = 0; I != NumFromArgs; ++I) { | |||
1891 | if (auto ToOrErr = import(FromArgs[I])) | |||
1892 | ToArgs.push_back(*ToOrErr); | |||
1893 | else | |||
1894 | return ToOrErr.takeError(); | |||
1895 | } | |||
1896 | ||||
1897 | return Error::success(); | |||
1898 | } | |||
1899 | ||||
1900 | // FIXME: Do not forget to remove this and use only 'import'. | |||
1901 | Expected<TemplateArgument> | |||
1902 | ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { | |||
1903 | return import(From); | |||
1904 | } | |||
1905 | ||||
1906 | template <typename InContainerTy> | |||
1907 | Error ASTNodeImporter::ImportTemplateArgumentListInfo( | |||
1908 | const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) { | |||
1909 | for (const auto &FromLoc : Container) { | |||
1910 | if (auto ToLocOrErr = import(FromLoc)) | |||
1911 | ToTAInfo.addArgument(*ToLocOrErr); | |||
1912 | else | |||
1913 | return ToLocOrErr.takeError(); | |||
1914 | } | |||
1915 | return Error::success(); | |||
1916 | } | |||
1917 | ||||
1918 | static StructuralEquivalenceKind | |||
1919 | getStructuralEquivalenceKind(const ASTImporter &Importer) { | |||
1920 | return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal | |||
1921 | : StructuralEquivalenceKind::Default; | |||
1922 | } | |||
1923 | ||||
1924 | bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) { | |||
1925 | StructuralEquivalenceContext Ctx( | |||
1926 | Importer.getFromContext(), Importer.getToContext(), | |||
1927 | Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), | |||
1928 | false, Complain); | |||
1929 | return Ctx.IsEquivalent(From, To); | |||
1930 | } | |||
1931 | ||||
1932 | bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord, | |||
1933 | RecordDecl *ToRecord, bool Complain) { | |||
1934 | // Eliminate a potential failure point where we attempt to re-import | |||
1935 | // something we're trying to import while completing ToRecord. | |||
1936 | Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord); | |||
1937 | if (ToOrigin) { | |||
1938 | auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin); | |||
1939 | if (ToOriginRecord) | |||
1940 | ToRecord = ToOriginRecord; | |||
1941 | } | |||
1942 | ||||
1943 | StructuralEquivalenceContext Ctx(Importer.getFromContext(), | |||
1944 | ToRecord->getASTContext(), | |||
1945 | Importer.getNonEquivalentDecls(), | |||
1946 | getStructuralEquivalenceKind(Importer), | |||
1947 | false, Complain); | |||
1948 | return Ctx.IsEquivalent(FromRecord, ToRecord); | |||
1949 | } | |||
1950 | ||||
1951 | bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, | |||
1952 | bool Complain) { | |||
1953 | StructuralEquivalenceContext Ctx( | |||
1954 | Importer.getFromContext(), Importer.getToContext(), | |||
1955 | Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), | |||
1956 | false, Complain); | |||
1957 | return Ctx.IsEquivalent(FromVar, ToVar); | |||
1958 | } | |||
1959 | ||||
1960 | bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) { | |||
1961 | // Eliminate a potential failure point where we attempt to re-import | |||
1962 | // something we're trying to import while completing ToEnum. | |||
1963 | if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum)) | |||
1964 | if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin)) | |||
1965 | ToEnum = ToOriginEnum; | |||
1966 | ||||
1967 | StructuralEquivalenceContext Ctx( | |||
1968 | Importer.getFromContext(), Importer.getToContext(), | |||
1969 | Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer)); | |||
1970 | return Ctx.IsEquivalent(FromEnum, ToEnum); | |||
1971 | } | |||
1972 | ||||
1973 | bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From, | |||
1974 | FunctionTemplateDecl *To) { | |||
1975 | StructuralEquivalenceContext Ctx( | |||
1976 | Importer.getFromContext(), Importer.getToContext(), | |||
1977 | Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), | |||
1978 | false, false); | |||
1979 | return Ctx.IsEquivalent(From, To); | |||
1980 | } | |||
1981 | ||||
1982 | bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) { | |||
1983 | StructuralEquivalenceContext Ctx( | |||
1984 | Importer.getFromContext(), Importer.getToContext(), | |||
1985 | Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), | |||
1986 | false, false); | |||
1987 | return Ctx.IsEquivalent(From, To); | |||
1988 | } | |||
1989 | ||||
1990 | bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC, | |||
1991 | EnumConstantDecl *ToEC) { | |||
1992 | const llvm::APSInt &FromVal = FromEC->getInitVal(); | |||
1993 | const llvm::APSInt &ToVal = ToEC->getInitVal(); | |||
1994 | ||||
1995 | return FromVal.isSigned() == ToVal.isSigned() && | |||
1996 | FromVal.getBitWidth() == ToVal.getBitWidth() && | |||
1997 | FromVal == ToVal; | |||
1998 | } | |||
1999 | ||||
2000 | bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From, | |||
2001 | ClassTemplateDecl *To) { | |||
2002 | StructuralEquivalenceContext Ctx(Importer.getFromContext(), | |||
2003 | Importer.getToContext(), | |||
2004 | Importer.getNonEquivalentDecls(), | |||
2005 | getStructuralEquivalenceKind(Importer)); | |||
2006 | return Ctx.IsEquivalent(From, To); | |||
2007 | } | |||
2008 | ||||
2009 | bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From, | |||
2010 | VarTemplateDecl *To) { | |||
2011 | StructuralEquivalenceContext Ctx(Importer.getFromContext(), | |||
2012 | Importer.getToContext(), | |||
2013 | Importer.getNonEquivalentDecls(), | |||
2014 | getStructuralEquivalenceKind(Importer)); | |||
2015 | return Ctx.IsEquivalent(From, To); | |||
2016 | } | |||
2017 | ||||
2018 | ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) { | |||
2019 | Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) | |||
2020 | << D->getDeclKindName(); | |||
2021 | return make_error<ImportError>(ImportError::UnsupportedConstruct); | |||
2022 | } | |||
2023 | ||||
2024 | ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) { | |||
2025 | Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) | |||
2026 | << D->getDeclKindName(); | |||
2027 | return make_error<ImportError>(ImportError::UnsupportedConstruct); | |||
2028 | } | |||
2029 | ||||
2030 | ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) { | |||
2031 | // Import the context of this declaration. | |||
2032 | DeclContext *DC, *LexicalDC; | |||
2033 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
2034 | return std::move(Err); | |||
2035 | ||||
2036 | // Import the location of this declaration. | |||
2037 | ExpectedSLoc LocOrErr = import(D->getLocation()); | |||
2038 | if (!LocOrErr) | |||
2039 | return LocOrErr.takeError(); | |||
2040 | ||||
2041 | EmptyDecl *ToD; | |||
2042 | if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr)) | |||
2043 | return ToD; | |||
2044 | ||||
2045 | ToD->setLexicalDeclContext(LexicalDC); | |||
2046 | LexicalDC->addDeclInternal(ToD); | |||
2047 | return ToD; | |||
2048 | } | |||
2049 | ||||
2050 | ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { | |||
2051 | TranslationUnitDecl *ToD = | |||
2052 | Importer.getToContext().getTranslationUnitDecl(); | |||
2053 | ||||
2054 | Importer.MapImported(D, ToD); | |||
2055 | ||||
2056 | return ToD; | |||
2057 | } | |||
2058 | ||||
2059 | ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) { | |||
2060 | ExpectedSLoc LocOrErr = import(D->getLocation()); | |||
2061 | if (!LocOrErr) | |||
2062 | return LocOrErr.takeError(); | |||
2063 | auto ColonLocOrErr = import(D->getColonLoc()); | |||
2064 | if (!ColonLocOrErr) | |||
2065 | return ColonLocOrErr.takeError(); | |||
2066 | ||||
2067 | // Import the context of this declaration. | |||
2068 | auto DCOrErr = Importer.ImportContext(D->getDeclContext()); | |||
2069 | if (!DCOrErr) | |||
2070 | return DCOrErr.takeError(); | |||
2071 | DeclContext *DC = *DCOrErr; | |||
2072 | ||||
2073 | AccessSpecDecl *ToD; | |||
2074 | if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(), | |||
2075 | DC, *LocOrErr, *ColonLocOrErr)) | |||
2076 | return ToD; | |||
2077 | ||||
2078 | // Lexical DeclContext and Semantic DeclContext | |||
2079 | // is always the same for the accessSpec. | |||
2080 | ToD->setLexicalDeclContext(DC); | |||
2081 | DC->addDeclInternal(ToD); | |||
2082 | ||||
2083 | return ToD; | |||
2084 | } | |||
2085 | ||||
2086 | ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) { | |||
2087 | auto DCOrErr = Importer.ImportContext(D->getDeclContext()); | |||
2088 | if (!DCOrErr) | |||
2089 | return DCOrErr.takeError(); | |||
2090 | DeclContext *DC = *DCOrErr; | |||
2091 | DeclContext *LexicalDC = DC; | |||
2092 | ||||
2093 | SourceLocation ToLocation, ToRParenLoc; | |||
2094 | Expr *ToAssertExpr; | |||
2095 | StringLiteral *ToMessage; | |||
2096 | if (auto Imp = importSeq( | |||
2097 | D->getLocation(), D->getAssertExpr(), D->getMessage(), D->getRParenLoc())) | |||
2098 | std::tie(ToLocation, ToAssertExpr, ToMessage, ToRParenLoc) = *Imp; | |||
2099 | else | |||
2100 | return Imp.takeError(); | |||
2101 | ||||
2102 | StaticAssertDecl *ToD; | |||
2103 | if (GetImportedOrCreateDecl( | |||
2104 | ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage, | |||
2105 | ToRParenLoc, D->isFailed())) | |||
2106 | return ToD; | |||
2107 | ||||
2108 | ToD->setLexicalDeclContext(LexicalDC); | |||
2109 | LexicalDC->addDeclInternal(ToD); | |||
2110 | return ToD; | |||
2111 | } | |||
2112 | ||||
2113 | ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { | |||
2114 | // Import the major distinguishing characteristics of this namespace. | |||
2115 | DeclContext *DC, *LexicalDC; | |||
2116 | DeclarationName Name; | |||
2117 | SourceLocation Loc; | |||
2118 | NamedDecl *ToD; | |||
2119 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
2120 | return std::move(Err); | |||
2121 | if (ToD) | |||
2122 | return ToD; | |||
2123 | ||||
2124 | NamespaceDecl *MergeWithNamespace = nullptr; | |||
2125 | if (!Name) { | |||
2126 | // This is an anonymous namespace. Adopt an existing anonymous | |||
2127 | // namespace if we can. | |||
2128 | // FIXME: Not testable. | |||
2129 | if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) | |||
2130 | MergeWithNamespace = TU->getAnonymousNamespace(); | |||
2131 | else | |||
2132 | MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace(); | |||
2133 | } else { | |||
2134 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
2135 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
2136 | for (auto *FoundDecl : FoundDecls) { | |||
2137 | if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace)) | |||
2138 | continue; | |||
2139 | ||||
2140 | if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) { | |||
2141 | MergeWithNamespace = FoundNS; | |||
2142 | ConflictingDecls.clear(); | |||
2143 | break; | |||
2144 | } | |||
2145 | ||||
2146 | ConflictingDecls.push_back(FoundDecl); | |||
2147 | } | |||
2148 | ||||
2149 | if (!ConflictingDecls.empty()) { | |||
2150 | Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace, | |||
2151 | ConflictingDecls.data(), | |||
2152 | ConflictingDecls.size()); | |||
2153 | if (!Name) | |||
2154 | return make_error<ImportError>(ImportError::NameConflict); | |||
2155 | } | |||
2156 | } | |||
2157 | ||||
2158 | ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); | |||
2159 | if (!BeginLocOrErr) | |||
2160 | return BeginLocOrErr.takeError(); | |||
2161 | ||||
2162 | // Create the "to" namespace, if needed. | |||
2163 | NamespaceDecl *ToNamespace = MergeWithNamespace; | |||
2164 | if (!ToNamespace) { | |||
2165 | if (GetImportedOrCreateDecl( | |||
2166 | ToNamespace, D, Importer.getToContext(), DC, D->isInline(), | |||
2167 | *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), | |||
2168 | /*PrevDecl=*/nullptr)) | |||
2169 | return ToNamespace; | |||
2170 | ToNamespace->setLexicalDeclContext(LexicalDC); | |||
2171 | LexicalDC->addDeclInternal(ToNamespace); | |||
2172 | ||||
2173 | // If this is an anonymous namespace, register it as the anonymous | |||
2174 | // namespace within its context. | |||
2175 | if (!Name) { | |||
2176 | if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) | |||
2177 | TU->setAnonymousNamespace(ToNamespace); | |||
2178 | else | |||
2179 | cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace); | |||
2180 | } | |||
2181 | } | |||
2182 | Importer.MapImported(D, ToNamespace); | |||
2183 | ||||
2184 | if (Error Err = ImportDeclContext(D)) | |||
2185 | return std::move(Err); | |||
2186 | ||||
2187 | return ToNamespace; | |||
2188 | } | |||
2189 | ||||
2190 | ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { | |||
2191 | // Import the major distinguishing characteristics of this namespace. | |||
2192 | DeclContext *DC, *LexicalDC; | |||
2193 | DeclarationName Name; | |||
2194 | SourceLocation Loc; | |||
2195 | NamedDecl *LookupD; | |||
2196 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc)) | |||
2197 | return std::move(Err); | |||
2198 | if (LookupD) | |||
2199 | return LookupD; | |||
2200 | ||||
2201 | // NOTE: No conflict resolution is done for namespace aliases now. | |||
2202 | ||||
2203 | SourceLocation ToNamespaceLoc, ToAliasLoc, ToTargetNameLoc; | |||
2204 | NestedNameSpecifierLoc ToQualifierLoc; | |||
2205 | NamespaceDecl *ToNamespace; | |||
2206 | if (auto Imp = importSeq( | |||
2207 | D->getNamespaceLoc(), D->getAliasLoc(), D->getQualifierLoc(), | |||
2208 | D->getTargetNameLoc(), D->getNamespace())) | |||
2209 | std::tie( | |||
2210 | ToNamespaceLoc, ToAliasLoc, ToQualifierLoc, ToTargetNameLoc, | |||
2211 | ToNamespace) = *Imp; | |||
2212 | else | |||
2213 | return Imp.takeError(); | |||
2214 | IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier()); | |||
2215 | ||||
2216 | NamespaceAliasDecl *ToD; | |||
2217 | if (GetImportedOrCreateDecl( | |||
2218 | ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc, | |||
2219 | ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace)) | |||
2220 | return ToD; | |||
2221 | ||||
2222 | ToD->setLexicalDeclContext(LexicalDC); | |||
2223 | LexicalDC->addDeclInternal(ToD); | |||
2224 | ||||
2225 | return ToD; | |||
2226 | } | |||
2227 | ||||
2228 | ExpectedDecl | |||
2229 | ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { | |||
2230 | // Import the major distinguishing characteristics of this typedef. | |||
2231 | DeclContext *DC, *LexicalDC; | |||
2232 | DeclarationName Name; | |||
2233 | SourceLocation Loc; | |||
2234 | NamedDecl *ToD; | |||
2235 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
2236 | return std::move(Err); | |||
2237 | if (ToD) | |||
2238 | return ToD; | |||
2239 | ||||
2240 | // If this typedef is not in block scope, determine whether we've | |||
2241 | // seen a typedef with the same name (that we can merge with) or any | |||
2242 | // other entity by that name (which name lookup could conflict with). | |||
2243 | if (!DC->isFunctionOrMethod()) { | |||
2244 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
2245 | unsigned IDNS = Decl::IDNS_Ordinary; | |||
2246 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
2247 | for (auto *FoundDecl : FoundDecls) { | |||
2248 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
2249 | continue; | |||
2250 | if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { | |||
2251 | QualType FromUT = D->getUnderlyingType(); | |||
2252 | QualType FoundUT = FoundTypedef->getUnderlyingType(); | |||
2253 | if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) { | |||
2254 | // If the "From" context has a complete underlying type but we | |||
2255 | // already have a complete underlying type then return with that. | |||
2256 | if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType()) | |||
2257 | return Importer.MapImported(D, FoundTypedef); | |||
2258 | } | |||
2259 | // FIXME Handle redecl chain. | |||
2260 | break; | |||
2261 | } | |||
2262 | ||||
2263 | ConflictingDecls.push_back(FoundDecl); | |||
2264 | } | |||
2265 | ||||
2266 | if (!ConflictingDecls.empty()) { | |||
2267 | Name = Importer.HandleNameConflict(Name, DC, IDNS, | |||
2268 | ConflictingDecls.data(), | |||
2269 | ConflictingDecls.size()); | |||
2270 | if (!Name) | |||
2271 | return make_error<ImportError>(ImportError::NameConflict); | |||
2272 | } | |||
2273 | } | |||
2274 | ||||
2275 | QualType ToUnderlyingType; | |||
2276 | TypeSourceInfo *ToTypeSourceInfo; | |||
2277 | SourceLocation ToBeginLoc; | |||
2278 | if (auto Imp = importSeq( | |||
2279 | D->getUnderlyingType(), D->getTypeSourceInfo(), D->getBeginLoc())) | |||
2280 | std::tie(ToUnderlyingType, ToTypeSourceInfo, ToBeginLoc) = *Imp; | |||
2281 | else | |||
2282 | return Imp.takeError(); | |||
2283 | ||||
2284 | // Create the new typedef node. | |||
2285 | // FIXME: ToUnderlyingType is not used. | |||
2286 | TypedefNameDecl *ToTypedef; | |||
2287 | if (IsAlias) { | |||
2288 | if (GetImportedOrCreateDecl<TypeAliasDecl>( | |||
2289 | ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, | |||
2290 | Name.getAsIdentifierInfo(), ToTypeSourceInfo)) | |||
2291 | return ToTypedef; | |||
2292 | } else if (GetImportedOrCreateDecl<TypedefDecl>( | |||
2293 | ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, | |||
2294 | Name.getAsIdentifierInfo(), ToTypeSourceInfo)) | |||
2295 | return ToTypedef; | |||
2296 | ||||
2297 | ToTypedef->setAccess(D->getAccess()); | |||
2298 | ToTypedef->setLexicalDeclContext(LexicalDC); | |||
2299 | ||||
2300 | // Templated declarations should not appear in DeclContext. | |||
2301 | TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr; | |||
2302 | if (!FromAlias || !FromAlias->getDescribedAliasTemplate()) | |||
2303 | LexicalDC->addDeclInternal(ToTypedef); | |||
2304 | ||||
2305 | return ToTypedef; | |||
2306 | } | |||
2307 | ||||
2308 | ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) { | |||
2309 | return VisitTypedefNameDecl(D, /*IsAlias=*/false); | |||
2310 | } | |||
2311 | ||||
2312 | ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) { | |||
2313 | return VisitTypedefNameDecl(D, /*IsAlias=*/true); | |||
2314 | } | |||
2315 | ||||
2316 | ExpectedDecl | |||
2317 | ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { | |||
2318 | // Import the major distinguishing characteristics of this typedef. | |||
2319 | DeclContext *DC, *LexicalDC; | |||
2320 | DeclarationName Name; | |||
2321 | SourceLocation Loc; | |||
2322 | NamedDecl *FoundD; | |||
2323 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc)) | |||
2324 | return std::move(Err); | |||
2325 | if (FoundD) | |||
2326 | return FoundD; | |||
2327 | ||||
2328 | // If this typedef is not in block scope, determine whether we've | |||
2329 | // seen a typedef with the same name (that we can merge with) or any | |||
2330 | // other entity by that name (which name lookup could conflict with). | |||
2331 | if (!DC->isFunctionOrMethod()) { | |||
2332 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
2333 | unsigned IDNS = Decl::IDNS_Ordinary; | |||
2334 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
2335 | for (auto *FoundDecl : FoundDecls) { | |||
2336 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
2337 | continue; | |||
2338 | if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl)) | |||
2339 | return Importer.MapImported(D, FoundAlias); | |||
2340 | ConflictingDecls.push_back(FoundDecl); | |||
2341 | } | |||
2342 | ||||
2343 | if (!ConflictingDecls.empty()) { | |||
2344 | Name = Importer.HandleNameConflict(Name, DC, IDNS, | |||
2345 | ConflictingDecls.data(), | |||
2346 | ConflictingDecls.size()); | |||
2347 | if (!Name) | |||
2348 | return make_error<ImportError>(ImportError::NameConflict); | |||
2349 | } | |||
2350 | } | |||
2351 | ||||
2352 | TemplateParameterList *ToTemplateParameters; | |||
2353 | TypeAliasDecl *ToTemplatedDecl; | |||
2354 | if (auto Imp = importSeq(D->getTemplateParameters(), D->getTemplatedDecl())) | |||
2355 | std::tie(ToTemplateParameters, ToTemplatedDecl) = *Imp; | |||
2356 | else | |||
2357 | return Imp.takeError(); | |||
2358 | ||||
2359 | TypeAliasTemplateDecl *ToAlias; | |||
2360 | if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc, | |||
2361 | Name, ToTemplateParameters, ToTemplatedDecl)) | |||
2362 | return ToAlias; | |||
2363 | ||||
2364 | ToTemplatedDecl->setDescribedAliasTemplate(ToAlias); | |||
2365 | ||||
2366 | ToAlias->setAccess(D->getAccess()); | |||
2367 | ToAlias->setLexicalDeclContext(LexicalDC); | |||
2368 | LexicalDC->addDeclInternal(ToAlias); | |||
2369 | return ToAlias; | |||
2370 | } | |||
2371 | ||||
2372 | ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) { | |||
2373 | // Import the major distinguishing characteristics of this label. | |||
2374 | DeclContext *DC, *LexicalDC; | |||
2375 | DeclarationName Name; | |||
2376 | SourceLocation Loc; | |||
2377 | NamedDecl *ToD; | |||
2378 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
2379 | return std::move(Err); | |||
2380 | if (ToD) | |||
2381 | return ToD; | |||
2382 | ||||
2383 | assert(LexicalDC->isFunctionOrMethod())((LexicalDC->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail ("LexicalDC->isFunctionOrMethod()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 2383, __PRETTY_FUNCTION__)); | |||
2384 | ||||
2385 | LabelDecl *ToLabel; | |||
2386 | if (D->isGnuLocal()) { | |||
2387 | ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); | |||
2388 | if (!BeginLocOrErr) | |||
2389 | return BeginLocOrErr.takeError(); | |||
2390 | if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, | |||
2391 | Name.getAsIdentifierInfo(), *BeginLocOrErr)) | |||
2392 | return ToLabel; | |||
2393 | ||||
2394 | } else { | |||
2395 | if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, | |||
2396 | Name.getAsIdentifierInfo())) | |||
2397 | return ToLabel; | |||
2398 | ||||
2399 | } | |||
2400 | ||||
2401 | Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt()); | |||
2402 | if (!ToStmtOrErr) | |||
2403 | return ToStmtOrErr.takeError(); | |||
2404 | ||||
2405 | ToLabel->setStmt(*ToStmtOrErr); | |||
2406 | ToLabel->setLexicalDeclContext(LexicalDC); | |||
2407 | LexicalDC->addDeclInternal(ToLabel); | |||
2408 | return ToLabel; | |||
2409 | } | |||
2410 | ||||
2411 | ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { | |||
2412 | // Import the major distinguishing characteristics of this enum. | |||
2413 | DeclContext *DC, *LexicalDC; | |||
2414 | DeclarationName Name; | |||
2415 | SourceLocation Loc; | |||
2416 | NamedDecl *ToD; | |||
2417 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
2418 | return std::move(Err); | |||
2419 | if (ToD) | |||
2420 | return ToD; | |||
2421 | ||||
2422 | // Figure out what enum name we're looking for. | |||
2423 | unsigned IDNS = Decl::IDNS_Tag; | |||
2424 | DeclarationName SearchName = Name; | |||
2425 | if (!SearchName && D->getTypedefNameForAnonDecl()) { | |||
2426 | if (Error Err = importInto( | |||
2427 | SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) | |||
2428 | return std::move(Err); | |||
2429 | IDNS = Decl::IDNS_Ordinary; | |||
2430 | } else if (Importer.getToContext().getLangOpts().CPlusPlus) | |||
2431 | IDNS |= Decl::IDNS_Ordinary; | |||
2432 | ||||
2433 | // We may already have an enum of the same name; try to find and match it. | |||
2434 | if (!DC->isFunctionOrMethod() && SearchName) { | |||
2435 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
2436 | auto FoundDecls = | |||
2437 | Importer.findDeclsInToCtx(DC, SearchName); | |||
2438 | for (auto *FoundDecl : FoundDecls) { | |||
2439 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
2440 | continue; | |||
2441 | ||||
2442 | if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { | |||
2443 | if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) | |||
2444 | FoundDecl = Tag->getDecl(); | |||
2445 | } | |||
2446 | ||||
2447 | if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) { | |||
2448 | if (IsStructuralMatch(D, FoundEnum)) | |||
2449 | return Importer.MapImported(D, FoundEnum); | |||
2450 | } | |||
2451 | ||||
2452 | ConflictingDecls.push_back(FoundDecl); | |||
2453 | } | |||
2454 | ||||
2455 | if (!ConflictingDecls.empty()) { | |||
2456 | Name = Importer.HandleNameConflict(SearchName, DC, IDNS, | |||
2457 | ConflictingDecls.data(), | |||
2458 | ConflictingDecls.size()); | |||
2459 | if (!Name) | |||
2460 | return make_error<ImportError>(ImportError::NameConflict); | |||
2461 | } | |||
2462 | } | |||
2463 | ||||
2464 | SourceLocation ToBeginLoc; | |||
2465 | NestedNameSpecifierLoc ToQualifierLoc; | |||
2466 | QualType ToIntegerType; | |||
2467 | if (auto Imp = importSeq( | |||
2468 | D->getBeginLoc(), D->getQualifierLoc(), D->getIntegerType())) | |||
2469 | std::tie(ToBeginLoc, ToQualifierLoc, ToIntegerType) = *Imp; | |||
2470 | else | |||
2471 | return Imp.takeError(); | |||
2472 | ||||
2473 | // Create the enum declaration. | |||
2474 | EnumDecl *D2; | |||
2475 | if (GetImportedOrCreateDecl( | |||
2476 | D2, D, Importer.getToContext(), DC, ToBeginLoc, | |||
2477 | Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(), | |||
2478 | D->isScopedUsingClassTag(), D->isFixed())) | |||
2479 | return D2; | |||
2480 | ||||
2481 | D2->setQualifierInfo(ToQualifierLoc); | |||
2482 | D2->setIntegerType(ToIntegerType); | |||
2483 | D2->setAccess(D->getAccess()); | |||
2484 | D2->setLexicalDeclContext(LexicalDC); | |||
2485 | LexicalDC->addDeclInternal(D2); | |||
2486 | ||||
2487 | // Import the definition | |||
2488 | if (D->isCompleteDefinition()) | |||
2489 | if (Error Err = ImportDefinition(D, D2)) | |||
2490 | return std::move(Err); | |||
2491 | ||||
2492 | return D2; | |||
2493 | } | |||
2494 | ||||
2495 | ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { | |||
2496 | bool IsFriendTemplate = false; | |||
2497 | if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { | |||
2498 | IsFriendTemplate = | |||
2499 | DCXX->getDescribedClassTemplate() && | |||
2500 | DCXX->getDescribedClassTemplate()->getFriendObjectKind() != | |||
2501 | Decl::FOK_None; | |||
2502 | } | |||
2503 | ||||
2504 | // Import the major distinguishing characteristics of this record. | |||
2505 | DeclContext *DC, *LexicalDC; | |||
2506 | DeclarationName Name; | |||
2507 | SourceLocation Loc; | |||
2508 | NamedDecl *ToD; | |||
2509 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
2510 | return std::move(Err); | |||
2511 | if (ToD) | |||
2512 | return ToD; | |||
2513 | ||||
2514 | // Figure out what structure name we're looking for. | |||
2515 | unsigned IDNS = Decl::IDNS_Tag; | |||
2516 | DeclarationName SearchName = Name; | |||
2517 | if (!SearchName && D->getTypedefNameForAnonDecl()) { | |||
2518 | if (Error Err = importInto( | |||
2519 | SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) | |||
2520 | return std::move(Err); | |||
2521 | IDNS = Decl::IDNS_Ordinary; | |||
2522 | } else if (Importer.getToContext().getLangOpts().CPlusPlus) | |||
2523 | IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend; | |||
2524 | ||||
2525 | // We may already have a record of the same name; try to find and match it. | |||
2526 | RecordDecl *PrevDecl = nullptr; | |||
2527 | if (!DC->isFunctionOrMethod()) { | |||
2528 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
2529 | auto FoundDecls = | |||
2530 | Importer.findDeclsInToCtx(DC, SearchName); | |||
2531 | if (!FoundDecls.empty()) { | |||
2532 | // We're going to have to compare D against potentially conflicting Decls, | |||
2533 | // so complete it. | |||
2534 | if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition()) | |||
2535 | D->getASTContext().getExternalSource()->CompleteType(D); | |||
2536 | } | |||
2537 | ||||
2538 | for (auto *FoundDecl : FoundDecls) { | |||
2539 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
2540 | continue; | |||
2541 | ||||
2542 | Decl *Found = FoundDecl; | |||
2543 | if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { | |||
2544 | if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) | |||
2545 | Found = Tag->getDecl(); | |||
2546 | } | |||
2547 | ||||
2548 | if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) { | |||
2549 | // Do not emit false positive diagnostic in case of unnamed | |||
2550 | // struct/union and in case of anonymous structs. Would be false | |||
2551 | // because there may be several anonymous/unnamed structs in a class. | |||
2552 | // E.g. these are both valid: | |||
2553 | // struct A { // unnamed structs | |||
2554 | // struct { struct A *next; } entry0; | |||
2555 | // struct { struct A *next; } entry1; | |||
2556 | // }; | |||
2557 | // struct X { struct { int a; }; struct { int b; }; }; // anon structs | |||
2558 | if (!SearchName) | |||
2559 | if (!IsStructuralMatch(D, FoundRecord, false)) | |||
2560 | continue; | |||
2561 | ||||
2562 | if (!hasSameVisibilityContext(FoundRecord, D)) | |||
2563 | continue; | |||
2564 | ||||
2565 | if (IsStructuralMatch(D, FoundRecord)) { | |||
2566 | RecordDecl *FoundDef = FoundRecord->getDefinition(); | |||
2567 | if (D->isThisDeclarationADefinition() && FoundDef) { | |||
2568 | // FIXME: Structural equivalence check should check for same | |||
2569 | // user-defined methods. | |||
2570 | Importer.MapImported(D, FoundDef); | |||
2571 | if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { | |||
2572 | auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef); | |||
2573 | assert(FoundCXX && "Record type mismatch")((FoundCXX && "Record type mismatch") ? static_cast< void> (0) : __assert_fail ("FoundCXX && \"Record type mismatch\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 2573, __PRETTY_FUNCTION__)); | |||
2574 | ||||
2575 | if (!Importer.isMinimalImport()) | |||
2576 | // FoundDef may not have every implicit method that D has | |||
2577 | // because implicit methods are created only if they are used. | |||
2578 | if (Error Err = ImportImplicitMethods(DCXX, FoundCXX)) | |||
2579 | return std::move(Err); | |||
2580 | } | |||
2581 | } | |||
2582 | PrevDecl = FoundRecord->getMostRecentDecl(); | |||
2583 | break; | |||
2584 | } | |||
2585 | } | |||
2586 | ||||
2587 | ConflictingDecls.push_back(FoundDecl); | |||
2588 | } // for | |||
2589 | ||||
2590 | if (!ConflictingDecls.empty() && SearchName) { | |||
2591 | Name = Importer.HandleNameConflict(SearchName, DC, IDNS, | |||
2592 | ConflictingDecls.data(), | |||
2593 | ConflictingDecls.size()); | |||
2594 | if (!Name) | |||
2595 | return make_error<ImportError>(ImportError::NameConflict); | |||
2596 | } | |||
2597 | } | |||
2598 | ||||
2599 | ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); | |||
2600 | if (!BeginLocOrErr) | |||
2601 | return BeginLocOrErr.takeError(); | |||
2602 | ||||
2603 | // Create the record declaration. | |||
2604 | RecordDecl *D2 = nullptr; | |||
2605 | CXXRecordDecl *D2CXX = nullptr; | |||
2606 | if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { | |||
2607 | if (DCXX->isLambda()) { | |||
2608 | auto TInfoOrErr = import(DCXX->getLambdaTypeInfo()); | |||
2609 | if (!TInfoOrErr) | |||
2610 | return TInfoOrErr.takeError(); | |||
2611 | if (GetImportedOrCreateSpecialDecl( | |||
2612 | D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(), | |||
2613 | DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(), | |||
2614 | DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault())) | |||
2615 | return D2CXX; | |||
2616 | ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl()); | |||
2617 | if (!CDeclOrErr) | |||
2618 | return CDeclOrErr.takeError(); | |||
2619 | D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr); | |||
2620 | } else if (DCXX->isInjectedClassName()) { | |||
2621 | // We have to be careful to do a similar dance to the one in | |||
2622 | // Sema::ActOnStartCXXMemberDeclarations | |||
2623 | const bool DelayTypeCreation = true; | |||
2624 | if (GetImportedOrCreateDecl( | |||
2625 | D2CXX, D, Importer.getToContext(), D->getTagKind(), DC, | |||
2626 | *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), | |||
2627 | cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation)) | |||
2628 | return D2CXX; | |||
2629 | Importer.getToContext().getTypeDeclType( | |||
2630 | D2CXX, dyn_cast<CXXRecordDecl>(DC)); | |||
2631 | } else { | |||
2632 | if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(), | |||
2633 | D->getTagKind(), DC, *BeginLocOrErr, Loc, | |||
2634 | Name.getAsIdentifierInfo(), | |||
2635 | cast_or_null<CXXRecordDecl>(PrevDecl))) | |||
2636 | return D2CXX; | |||
2637 | } | |||
2638 | ||||
2639 | D2 = D2CXX; | |||
2640 | D2->setAccess(D->getAccess()); | |||
2641 | D2->setLexicalDeclContext(LexicalDC); | |||
2642 | if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit()) | |||
2643 | LexicalDC->addDeclInternal(D2); | |||
2644 | ||||
2645 | if (LexicalDC != DC && D->isInIdentifierNamespace(Decl::IDNS_TagFriend)) | |||
2646 | DC->makeDeclVisibleInContext(D2); | |||
2647 | ||||
2648 | if (ClassTemplateDecl *FromDescribed = | |||
2649 | DCXX->getDescribedClassTemplate()) { | |||
2650 | ClassTemplateDecl *ToDescribed; | |||
2651 | if (Error Err = importInto(ToDescribed, FromDescribed)) | |||
2652 | return std::move(Err); | |||
2653 | D2CXX->setDescribedClassTemplate(ToDescribed); | |||
2654 | if (!DCXX->isInjectedClassName() && !IsFriendTemplate) { | |||
2655 | // In a record describing a template the type should be an | |||
2656 | // InjectedClassNameType (see Sema::CheckClassTemplate). Update the | |||
2657 | // previously set type to the correct value here (ToDescribed is not | |||
2658 | // available at record create). | |||
2659 | // FIXME: The previous type is cleared but not removed from | |||
2660 | // ASTContext's internal storage. | |||
2661 | CXXRecordDecl *Injected = nullptr; | |||
2662 | for (NamedDecl *Found : D2CXX->noload_lookup(Name)) { | |||
2663 | auto *Record = dyn_cast<CXXRecordDecl>(Found); | |||
2664 | if (Record && Record->isInjectedClassName()) { | |||
2665 | Injected = Record; | |||
2666 | break; | |||
2667 | } | |||
2668 | } | |||
2669 | // Create an injected type for the whole redecl chain. | |||
2670 | SmallVector<Decl *, 2> Redecls = | |||
2671 | getCanonicalForwardRedeclChain(D2CXX); | |||
2672 | for (auto *R : Redecls) { | |||
2673 | auto *RI = cast<CXXRecordDecl>(R); | |||
2674 | RI->setTypeForDecl(nullptr); | |||
2675 | // Below we create a new injected type and assign that to the | |||
2676 | // canonical decl, subsequent declarations in the chain will reuse | |||
2677 | // that type. | |||
2678 | Importer.getToContext().getInjectedClassNameType( | |||
2679 | RI, ToDescribed->getInjectedClassNameSpecialization()); | |||
2680 | } | |||
2681 | // Set the new type for the previous injected decl too. | |||
2682 | if (Injected) { | |||
2683 | Injected->setTypeForDecl(nullptr); | |||
2684 | Importer.getToContext().getTypeDeclType(Injected, D2CXX); | |||
2685 | } | |||
2686 | } | |||
2687 | } else if (MemberSpecializationInfo *MemberInfo = | |||
2688 | DCXX->getMemberSpecializationInfo()) { | |||
2689 | TemplateSpecializationKind SK = | |||
2690 | MemberInfo->getTemplateSpecializationKind(); | |||
2691 | CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass(); | |||
2692 | ||||
2693 | if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst)) | |||
2694 | D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK); | |||
2695 | else | |||
2696 | return ToInstOrErr.takeError(); | |||
2697 | ||||
2698 | if (ExpectedSLoc POIOrErr = | |||
2699 | import(MemberInfo->getPointOfInstantiation())) | |||
2700 | D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation( | |||
2701 | *POIOrErr); | |||
2702 | else | |||
2703 | return POIOrErr.takeError(); | |||
2704 | } | |||
2705 | ||||
2706 | } else { | |||
2707 | if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), | |||
2708 | D->getTagKind(), DC, *BeginLocOrErr, Loc, | |||
2709 | Name.getAsIdentifierInfo(), PrevDecl)) | |||
2710 | return D2; | |||
2711 | D2->setLexicalDeclContext(LexicalDC); | |||
2712 | LexicalDC->addDeclInternal(D2); | |||
2713 | } | |||
2714 | ||||
2715 | if (auto QualifierLocOrErr = import(D->getQualifierLoc())) | |||
2716 | D2->setQualifierInfo(*QualifierLocOrErr); | |||
2717 | else | |||
2718 | return QualifierLocOrErr.takeError(); | |||
2719 | ||||
2720 | if (D->isAnonymousStructOrUnion()) | |||
2721 | D2->setAnonymousStructOrUnion(true); | |||
2722 | ||||
2723 | if (D->isCompleteDefinition()) | |||
2724 | if (Error Err = ImportDefinition(D, D2, IDK_Default)) | |||
2725 | return std::move(Err); | |||
2726 | ||||
2727 | return D2; | |||
2728 | } | |||
2729 | ||||
2730 | ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { | |||
2731 | // Import the major distinguishing characteristics of this enumerator. | |||
2732 | DeclContext *DC, *LexicalDC; | |||
2733 | DeclarationName Name; | |||
2734 | SourceLocation Loc; | |||
2735 | NamedDecl *ToD; | |||
2736 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
2737 | return std::move(Err); | |||
2738 | if (ToD) | |||
2739 | return ToD; | |||
2740 | ||||
2741 | // Determine whether there are any other declarations with the same name and | |||
2742 | // in the same context. | |||
2743 | if (!LexicalDC->isFunctionOrMethod()) { | |||
2744 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
2745 | unsigned IDNS = Decl::IDNS_Ordinary; | |||
2746 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
2747 | for (auto *FoundDecl : FoundDecls) { | |||
2748 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
2749 | continue; | |||
2750 | ||||
2751 | if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) { | |||
2752 | if (IsStructuralMatch(D, FoundEnumConstant)) | |||
2753 | return Importer.MapImported(D, FoundEnumConstant); | |||
2754 | } | |||
2755 | ||||
2756 | ConflictingDecls.push_back(FoundDecl); | |||
2757 | } | |||
2758 | ||||
2759 | if (!ConflictingDecls.empty()) { | |||
2760 | Name = Importer.HandleNameConflict(Name, DC, IDNS, | |||
2761 | ConflictingDecls.data(), | |||
2762 | ConflictingDecls.size()); | |||
2763 | if (!Name) | |||
2764 | return make_error<ImportError>(ImportError::NameConflict); | |||
2765 | } | |||
2766 | } | |||
2767 | ||||
2768 | ExpectedType TypeOrErr = import(D->getType()); | |||
2769 | if (!TypeOrErr) | |||
2770 | return TypeOrErr.takeError(); | |||
2771 | ||||
2772 | ExpectedExpr InitOrErr = import(D->getInitExpr()); | |||
2773 | if (!InitOrErr) | |||
2774 | return InitOrErr.takeError(); | |||
2775 | ||||
2776 | EnumConstantDecl *ToEnumerator; | |||
2777 | if (GetImportedOrCreateDecl( | |||
2778 | ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc, | |||
2779 | Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal())) | |||
2780 | return ToEnumerator; | |||
2781 | ||||
2782 | ToEnumerator->setAccess(D->getAccess()); | |||
2783 | ToEnumerator->setLexicalDeclContext(LexicalDC); | |||
2784 | LexicalDC->addDeclInternal(ToEnumerator); | |||
2785 | return ToEnumerator; | |||
2786 | } | |||
2787 | ||||
2788 | Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD, | |||
2789 | DeclaratorDecl *ToD) { | |||
2790 | unsigned int Num = FromD->getNumTemplateParameterLists(); | |||
2791 | if (Num == 0) | |||
2792 | return Error::success(); | |||
2793 | SmallVector<TemplateParameterList *, 2> ToTPLists(Num); | |||
2794 | for (unsigned int I = 0; I < Num; ++I) | |||
2795 | if (Expected<TemplateParameterList *> ToTPListOrErr = | |||
2796 | import(FromD->getTemplateParameterList(I))) | |||
2797 | ToTPLists[I] = *ToTPListOrErr; | |||
2798 | else | |||
2799 | return ToTPListOrErr.takeError(); | |||
2800 | ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists); | |||
2801 | return Error::success(); | |||
2802 | } | |||
2803 | ||||
2804 | Error ASTNodeImporter::ImportTemplateInformation( | |||
2805 | FunctionDecl *FromFD, FunctionDecl *ToFD) { | |||
2806 | switch (FromFD->getTemplatedKind()) { | |||
2807 | case FunctionDecl::TK_NonTemplate: | |||
2808 | case FunctionDecl::TK_FunctionTemplate: | |||
2809 | return Error::success(); | |||
2810 | ||||
2811 | case FunctionDecl::TK_MemberSpecialization: { | |||
2812 | TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind(); | |||
2813 | ||||
2814 | if (Expected<FunctionDecl *> InstFDOrErr = | |||
2815 | import(FromFD->getInstantiatedFromMemberFunction())) | |||
2816 | ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK); | |||
2817 | else | |||
2818 | return InstFDOrErr.takeError(); | |||
2819 | ||||
2820 | if (ExpectedSLoc POIOrErr = import( | |||
2821 | FromFD->getMemberSpecializationInfo()->getPointOfInstantiation())) | |||
2822 | ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr); | |||
2823 | else | |||
2824 | return POIOrErr.takeError(); | |||
2825 | ||||
2826 | return Error::success(); | |||
2827 | } | |||
2828 | ||||
2829 | case FunctionDecl::TK_FunctionTemplateSpecialization: { | |||
2830 | auto FunctionAndArgsOrErr = | |||
2831 | ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); | |||
2832 | if (!FunctionAndArgsOrErr) | |||
2833 | return FunctionAndArgsOrErr.takeError(); | |||
2834 | ||||
2835 | TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy( | |||
2836 | Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr)); | |||
2837 | ||||
2838 | auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); | |||
2839 | TemplateArgumentListInfo ToTAInfo; | |||
2840 | const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten; | |||
2841 | if (FromTAArgsAsWritten) | |||
2842 | if (Error Err = ImportTemplateArgumentListInfo( | |||
2843 | *FromTAArgsAsWritten, ToTAInfo)) | |||
2844 | return Err; | |||
2845 | ||||
2846 | ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation()); | |||
2847 | if (!POIOrErr) | |||
2848 | return POIOrErr.takeError(); | |||
2849 | ||||
2850 | if (Error Err = ImportTemplateParameterLists(FromFD, ToFD)) | |||
2851 | return Err; | |||
2852 | ||||
2853 | TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind(); | |||
2854 | ToFD->setFunctionTemplateSpecialization( | |||
2855 | std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr, | |||
2856 | TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr); | |||
2857 | return Error::success(); | |||
2858 | } | |||
2859 | ||||
2860 | case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { | |||
2861 | auto *FromInfo = FromFD->getDependentSpecializationInfo(); | |||
2862 | UnresolvedSet<8> TemplDecls; | |||
2863 | unsigned NumTemplates = FromInfo->getNumTemplates(); | |||
2864 | for (unsigned I = 0; I < NumTemplates; I++) { | |||
2865 | if (Expected<FunctionTemplateDecl *> ToFTDOrErr = | |||
2866 | import(FromInfo->getTemplate(I))) | |||
2867 | TemplDecls.addDecl(*ToFTDOrErr); | |||
2868 | else | |||
2869 | return ToFTDOrErr.takeError(); | |||
2870 | } | |||
2871 | ||||
2872 | // Import TemplateArgumentListInfo. | |||
2873 | TemplateArgumentListInfo ToTAInfo; | |||
2874 | if (Error Err = ImportTemplateArgumentListInfo( | |||
2875 | FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(), | |||
2876 | llvm::makeArrayRef( | |||
2877 | FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()), | |||
2878 | ToTAInfo)) | |||
2879 | return Err; | |||
2880 | ||||
2881 | ToFD->setDependentTemplateSpecialization(Importer.getToContext(), | |||
2882 | TemplDecls, ToTAInfo); | |||
2883 | return Error::success(); | |||
2884 | } | |||
2885 | } | |||
2886 | llvm_unreachable("All cases should be covered!")::llvm::llvm_unreachable_internal("All cases should be covered!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 2886); | |||
2887 | } | |||
2888 | ||||
2889 | Expected<FunctionDecl *> | |||
2890 | ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) { | |||
2891 | auto FunctionAndArgsOrErr = | |||
2892 | ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); | |||
2893 | if (!FunctionAndArgsOrErr) | |||
2894 | return FunctionAndArgsOrErr.takeError(); | |||
2895 | ||||
2896 | FunctionTemplateDecl *Template; | |||
2897 | TemplateArgsTy ToTemplArgs; | |||
2898 | std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr; | |||
2899 | void *InsertPos = nullptr; | |||
2900 | auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos); | |||
2901 | return FoundSpec; | |||
2902 | } | |||
2903 | ||||
2904 | Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD, | |||
2905 | FunctionDecl *ToFD) { | |||
2906 | if (Stmt *FromBody = FromFD->getBody()) { | |||
2907 | if (ExpectedStmt ToBodyOrErr = import(FromBody)) | |||
2908 | ToFD->setBody(*ToBodyOrErr); | |||
2909 | else | |||
2910 | return ToBodyOrErr.takeError(); | |||
2911 | } | |||
2912 | return Error::success(); | |||
2913 | } | |||
2914 | ||||
2915 | template <typename T> | |||
2916 | bool ASTNodeImporter::hasSameVisibilityContext(T *Found, T *From) { | |||
2917 | if (From->hasExternalFormalLinkage()) | |||
2918 | return Found->hasExternalFormalLinkage(); | |||
2919 | if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl()) | |||
2920 | return false; | |||
2921 | if (From->isInAnonymousNamespace()) | |||
2922 | return Found->isInAnonymousNamespace(); | |||
2923 | else | |||
2924 | return !Found->isInAnonymousNamespace() && | |||
2925 | !Found->hasExternalFormalLinkage(); | |||
2926 | } | |||
2927 | ||||
2928 | ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { | |||
2929 | ||||
2930 | SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D); | |||
2931 | auto RedeclIt = Redecls.begin(); | |||
2932 | // Import the first part of the decl chain. I.e. import all previous | |||
2933 | // declarations starting from the canonical decl. | |||
2934 | for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { | |||
2935 | ExpectedDecl ToRedeclOrErr = import(*RedeclIt); | |||
2936 | if (!ToRedeclOrErr) | |||
2937 | return ToRedeclOrErr.takeError(); | |||
2938 | } | |||
2939 | assert(*RedeclIt == D)((*RedeclIt == D) ? static_cast<void> (0) : __assert_fail ("*RedeclIt == D", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 2939, __PRETTY_FUNCTION__)); | |||
2940 | ||||
2941 | // Import the major distinguishing characteristics of this function. | |||
2942 | DeclContext *DC, *LexicalDC; | |||
2943 | DeclarationName Name; | |||
2944 | SourceLocation Loc; | |||
2945 | NamedDecl *ToD; | |||
2946 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
2947 | return std::move(Err); | |||
2948 | if (ToD) | |||
2949 | return ToD; | |||
2950 | ||||
2951 | FunctionDecl *FoundByLookup = nullptr; | |||
2952 | FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate(); | |||
2953 | ||||
2954 | // If this is a function template specialization, then try to find the same | |||
2955 | // existing specialization in the "to" context. The lookup below will not | |||
2956 | // find any specialization, but would find the primary template; thus, we | |||
2957 | // have to skip normal lookup in case of specializations. | |||
2958 | // FIXME handle member function templates (TK_MemberSpecialization) similarly? | |||
2959 | if (D->getTemplatedKind() == | |||
2960 | FunctionDecl::TK_FunctionTemplateSpecialization) { | |||
2961 | auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D); | |||
2962 | if (!FoundFunctionOrErr) | |||
2963 | return FoundFunctionOrErr.takeError(); | |||
2964 | if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) { | |||
2965 | if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) | |||
2966 | return Def; | |||
2967 | FoundByLookup = FoundFunction; | |||
2968 | } | |||
2969 | } | |||
2970 | // Try to find a function in our own ("to") context with the same name, same | |||
2971 | // type, and in the same context as the function we're importing. | |||
2972 | else if (!LexicalDC->isFunctionOrMethod()) { | |||
2973 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
2974 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; | |||
2975 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
2976 | for (auto *FoundDecl : FoundDecls) { | |||
2977 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
2978 | continue; | |||
2979 | ||||
2980 | if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) { | |||
2981 | if (!hasSameVisibilityContext(FoundFunction, D)) | |||
2982 | continue; | |||
2983 | ||||
2984 | if (IsStructuralMatch(D, FoundFunction)) { | |||
2985 | if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) | |||
2986 | return Def; | |||
2987 | FoundByLookup = FoundFunction; | |||
2988 | break; | |||
2989 | } | |||
2990 | // FIXME: Check for overloading more carefully, e.g., by boosting | |||
2991 | // Sema::IsOverload out to the AST library. | |||
2992 | ||||
2993 | // Function overloading is okay in C++. | |||
2994 | if (Importer.getToContext().getLangOpts().CPlusPlus) | |||
2995 | continue; | |||
2996 | ||||
2997 | // Complain about inconsistent function types. | |||
2998 | Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent) | |||
2999 | << Name << D->getType() << FoundFunction->getType(); | |||
3000 | Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here) | |||
3001 | << FoundFunction->getType(); | |||
3002 | } | |||
3003 | ||||
3004 | ConflictingDecls.push_back(FoundDecl); | |||
3005 | } | |||
3006 | ||||
3007 | if (!ConflictingDecls.empty()) { | |||
3008 | Name = Importer.HandleNameConflict(Name, DC, IDNS, | |||
3009 | ConflictingDecls.data(), | |||
3010 | ConflictingDecls.size()); | |||
3011 | if (!Name) | |||
3012 | return make_error<ImportError>(ImportError::NameConflict); | |||
3013 | } | |||
3014 | } | |||
3015 | ||||
3016 | // We do not allow more than one in-class declaration of a function. This is | |||
3017 | // because AST clients like VTableBuilder asserts on this. VTableBuilder | |||
3018 | // assumes there is only one in-class declaration. Building a redecl | |||
3019 | // chain would result in more than one in-class declaration for | |||
3020 | // overrides (even if they are part of the same redecl chain inside the | |||
3021 | // derived class.) | |||
3022 | if (FoundByLookup) { | |||
3023 | if (isa<CXXMethodDecl>(FoundByLookup)) { | |||
3024 | if (D->getLexicalDeclContext() == D->getDeclContext()) { | |||
3025 | if (!D->doesThisDeclarationHaveABody()) | |||
3026 | return Importer.MapImported(D, FoundByLookup); | |||
3027 | else { | |||
3028 | // Let's continue and build up the redecl chain in this case. | |||
3029 | // FIXME Merge the functions into one decl. | |||
3030 | } | |||
3031 | } | |||
3032 | } | |||
3033 | } | |||
3034 | ||||
3035 | DeclarationNameInfo NameInfo(Name, Loc); | |||
3036 | // Import additional name location/type info. | |||
3037 | if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) | |||
3038 | return std::move(Err); | |||
3039 | ||||
3040 | QualType FromTy = D->getType(); | |||
3041 | bool usedDifferentExceptionSpec = false; | |||
3042 | ||||
3043 | if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) { | |||
3044 | FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo(); | |||
3045 | // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the | |||
3046 | // FunctionDecl that we are importing the FunctionProtoType for. | |||
3047 | // To avoid an infinite recursion when importing, create the FunctionDecl | |||
3048 | // with a simplified function type and update it afterwards. | |||
3049 | if (FromEPI.ExceptionSpec.SourceDecl || | |||
3050 | FromEPI.ExceptionSpec.SourceTemplate || | |||
3051 | FromEPI.ExceptionSpec.NoexceptExpr) { | |||
3052 | FunctionProtoType::ExtProtoInfo DefaultEPI; | |||
3053 | FromTy = Importer.getFromContext().getFunctionType( | |||
3054 | FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI); | |||
3055 | usedDifferentExceptionSpec = true; | |||
3056 | } | |||
3057 | } | |||
3058 | ||||
3059 | QualType T; | |||
3060 | TypeSourceInfo *TInfo; | |||
3061 | SourceLocation ToInnerLocStart, ToEndLoc; | |||
3062 | NestedNameSpecifierLoc ToQualifierLoc; | |||
3063 | if (auto Imp = importSeq( | |||
3064 | FromTy, D->getTypeSourceInfo(), D->getInnerLocStart(), | |||
3065 | D->getQualifierLoc(), D->getEndLoc())) | |||
3066 | std::tie(T, TInfo, ToInnerLocStart, ToQualifierLoc, ToEndLoc) = *Imp; | |||
3067 | else | |||
3068 | return Imp.takeError(); | |||
3069 | ||||
3070 | // Import the function parameters. | |||
3071 | SmallVector<ParmVarDecl *, 8> Parameters; | |||
3072 | for (auto P : D->parameters()) { | |||
3073 | if (Expected<ParmVarDecl *> ToPOrErr = import(P)) | |||
3074 | Parameters.push_back(*ToPOrErr); | |||
3075 | else | |||
3076 | return ToPOrErr.takeError(); | |||
3077 | } | |||
3078 | ||||
3079 | // Create the imported function. | |||
3080 | FunctionDecl *ToFunction = nullptr; | |||
3081 | if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { | |||
3082 | Expr *ExplicitExpr = nullptr; | |||
3083 | if (FromConstructor->getExplicitSpecifier().getExpr()) { | |||
3084 | auto Imp = importSeq(FromConstructor->getExplicitSpecifier().getExpr()); | |||
3085 | if (!Imp) | |||
3086 | return Imp.takeError(); | |||
3087 | std::tie(ExplicitExpr) = *Imp; | |||
3088 | } | |||
3089 | if (GetImportedOrCreateDecl<CXXConstructorDecl>( | |||
3090 | ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), | |||
3091 | ToInnerLocStart, NameInfo, T, TInfo, | |||
3092 | ExplicitSpecifier( | |||
3093 | ExplicitExpr, | |||
3094 | FromConstructor->getExplicitSpecifier().getKind()), | |||
3095 | D->isInlineSpecified(), D->isImplicit(), D->isConstexpr())) | |||
3096 | return ToFunction; | |||
3097 | } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) { | |||
3098 | ||||
3099 | auto Imp = | |||
3100 | importSeq(const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()), | |||
3101 | FromDtor->getOperatorDeleteThisArg()); | |||
3102 | ||||
3103 | if (!Imp) | |||
3104 | return Imp.takeError(); | |||
3105 | ||||
3106 | FunctionDecl *ToOperatorDelete; | |||
3107 | Expr *ToThisArg; | |||
3108 | std::tie(ToOperatorDelete, ToThisArg) = *Imp; | |||
3109 | ||||
3110 | if (GetImportedOrCreateDecl<CXXDestructorDecl>( | |||
3111 | ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), | |||
3112 | ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(), | |||
3113 | D->isImplicit())) | |||
3114 | return ToFunction; | |||
3115 | ||||
3116 | CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction); | |||
3117 | ||||
3118 | ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg); | |||
3119 | } else if (CXXConversionDecl *FromConversion = | |||
3120 | dyn_cast<CXXConversionDecl>(D)) { | |||
3121 | Expr *ExplicitExpr = nullptr; | |||
3122 | if (FromConversion->getExplicitSpecifier().getExpr()) { | |||
3123 | auto Imp = importSeq(FromConversion->getExplicitSpecifier().getExpr()); | |||
3124 | if (!Imp) | |||
3125 | return Imp.takeError(); | |||
3126 | std::tie(ExplicitExpr) = *Imp; | |||
3127 | } | |||
3128 | if (GetImportedOrCreateDecl<CXXConversionDecl>( | |||
3129 | ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), | |||
3130 | ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(), | |||
3131 | ExplicitSpecifier(ExplicitExpr, | |||
3132 | FromConversion->getExplicitSpecifier().getKind()), | |||
3133 | D->isConstexpr(), SourceLocation())) | |||
3134 | return ToFunction; | |||
3135 | } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) { | |||
3136 | if (GetImportedOrCreateDecl<CXXMethodDecl>( | |||
3137 | ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), | |||
3138 | ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(), | |||
3139 | Method->isInlineSpecified(), D->isConstexpr(), SourceLocation())) | |||
3140 | return ToFunction; | |||
3141 | } else { | |||
3142 | if (GetImportedOrCreateDecl(ToFunction, D, Importer.getToContext(), DC, | |||
3143 | ToInnerLocStart, NameInfo, T, TInfo, | |||
3144 | D->getStorageClass(), D->isInlineSpecified(), | |||
3145 | D->hasWrittenPrototype(), D->isConstexpr())) | |||
3146 | return ToFunction; | |||
3147 | } | |||
3148 | ||||
3149 | // Connect the redecl chain. | |||
3150 | if (FoundByLookup) { | |||
3151 | auto *Recent = const_cast<FunctionDecl *>( | |||
3152 | FoundByLookup->getMostRecentDecl()); | |||
3153 | ToFunction->setPreviousDecl(Recent); | |||
3154 | // FIXME Probably we should merge exception specifications. E.g. In the | |||
3155 | // "To" context the existing function may have exception specification with | |||
3156 | // noexcept-unevaluated, while the newly imported function may have an | |||
3157 | // evaluated noexcept. A call to adjustExceptionSpec() on the imported | |||
3158 | // decl and its redeclarations may be required. | |||
3159 | } | |||
3160 | ||||
3161 | // Import Ctor initializers. | |||
3162 | if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { | |||
3163 | if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) { | |||
3164 | SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers); | |||
3165 | // Import first, then allocate memory and copy if there was no error. | |||
3166 | if (Error Err = ImportContainerChecked( | |||
3167 | FromConstructor->inits(), CtorInitializers)) | |||
3168 | return std::move(Err); | |||
3169 | auto **Memory = | |||
3170 | new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers]; | |||
3171 | std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory); | |||
3172 | auto *ToCtor = cast<CXXConstructorDecl>(ToFunction); | |||
3173 | ToCtor->setCtorInitializers(Memory); | |||
3174 | ToCtor->setNumCtorInitializers(NumInitializers); | |||
3175 | } | |||
3176 | } | |||
3177 | ||||
3178 | ToFunction->setQualifierInfo(ToQualifierLoc); | |||
3179 | ToFunction->setAccess(D->getAccess()); | |||
3180 | ToFunction->setLexicalDeclContext(LexicalDC); | |||
3181 | ToFunction->setVirtualAsWritten(D->isVirtualAsWritten()); | |||
3182 | ToFunction->setTrivial(D->isTrivial()); | |||
3183 | ToFunction->setPure(D->isPure()); | |||
3184 | ToFunction->setRangeEnd(ToEndLoc); | |||
3185 | ||||
3186 | // Set the parameters. | |||
3187 | for (auto *Param : Parameters) { | |||
3188 | Param->setOwningFunction(ToFunction); | |||
3189 | ToFunction->addDeclInternal(Param); | |||
3190 | } | |||
3191 | ToFunction->setParams(Parameters); | |||
3192 | ||||
3193 | // We need to complete creation of FunctionProtoTypeLoc manually with setting | |||
3194 | // params it refers to. | |||
3195 | if (TInfo) { | |||
3196 | if (auto ProtoLoc = | |||
3197 | TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) { | |||
3198 | for (unsigned I = 0, N = Parameters.size(); I != N; ++I) | |||
3199 | ProtoLoc.setParam(I, Parameters[I]); | |||
3200 | } | |||
3201 | } | |||
3202 | ||||
3203 | if (usedDifferentExceptionSpec) { | |||
3204 | // Update FunctionProtoType::ExtProtoInfo. | |||
3205 | if (ExpectedType TyOrErr = import(D->getType())) | |||
3206 | ToFunction->setType(*TyOrErr); | |||
3207 | else | |||
3208 | return TyOrErr.takeError(); | |||
3209 | } | |||
3210 | ||||
3211 | // Import the describing template function, if any. | |||
3212 | if (FromFT) { | |||
3213 | auto ToFTOrErr = import(FromFT); | |||
3214 | if (!ToFTOrErr) | |||
3215 | return ToFTOrErr.takeError(); | |||
3216 | } | |||
3217 | ||||
3218 | if (D->doesThisDeclarationHaveABody()) { | |||
3219 | Error Err = ImportFunctionDeclBody(D, ToFunction); | |||
3220 | ||||
3221 | if (Err) | |||
3222 | return std::move(Err); | |||
3223 | } | |||
3224 | ||||
3225 | // FIXME: Other bits to merge? | |||
3226 | ||||
3227 | // If it is a template, import all related things. | |||
3228 | if (Error Err = ImportTemplateInformation(D, ToFunction)) | |||
3229 | return std::move(Err); | |||
3230 | ||||
3231 | bool IsFriend = D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend); | |||
3232 | ||||
3233 | // TODO Can we generalize this approach to other AST nodes as well? | |||
3234 | if (D->getDeclContext()->containsDeclAndLoad(D)) | |||
3235 | DC->addDeclInternal(ToFunction); | |||
3236 | if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D)) | |||
3237 | LexicalDC->addDeclInternal(ToFunction); | |||
3238 | ||||
3239 | // Friend declaration's lexical context is the befriending class, but the | |||
3240 | // semantic context is the enclosing scope of the befriending class. | |||
3241 | // We want the friend functions to be found in the semantic context by lookup. | |||
3242 | // FIXME should we handle this generically in VisitFriendDecl? | |||
3243 | // In Other cases when LexicalDC != DC we don't want it to be added, | |||
3244 | // e.g out-of-class definitions like void B::f() {} . | |||
3245 | if (LexicalDC != DC && IsFriend) { | |||
3246 | DC->makeDeclVisibleInContext(ToFunction); | |||
3247 | } | |||
3248 | ||||
3249 | if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D)) | |||
3250 | ImportOverrides(cast<CXXMethodDecl>(ToFunction), FromCXXMethod); | |||
3251 | ||||
3252 | // Import the rest of the chain. I.e. import all subsequent declarations. | |||
3253 | for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { | |||
3254 | ExpectedDecl ToRedeclOrErr = import(*RedeclIt); | |||
3255 | if (!ToRedeclOrErr) | |||
3256 | return ToRedeclOrErr.takeError(); | |||
3257 | } | |||
3258 | ||||
3259 | return ToFunction; | |||
3260 | } | |||
3261 | ||||
3262 | ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) { | |||
3263 | return VisitFunctionDecl(D); | |||
3264 | } | |||
3265 | ||||
3266 | ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) { | |||
3267 | return VisitCXXMethodDecl(D); | |||
3268 | } | |||
3269 | ||||
3270 | ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) { | |||
3271 | return VisitCXXMethodDecl(D); | |||
3272 | } | |||
3273 | ||||
3274 | ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) { | |||
3275 | return VisitCXXMethodDecl(D); | |||
3276 | } | |||
3277 | ||||
3278 | ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { | |||
3279 | // Import the major distinguishing characteristics of a variable. | |||
3280 | DeclContext *DC, *LexicalDC; | |||
3281 | DeclarationName Name; | |||
3282 | SourceLocation Loc; | |||
3283 | NamedDecl *ToD; | |||
3284 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
3285 | return std::move(Err); | |||
3286 | if (ToD) | |||
3287 | return ToD; | |||
3288 | ||||
3289 | // Determine whether we've already imported this field. | |||
3290 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
3291 | for (auto *FoundDecl : FoundDecls) { | |||
3292 | if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) { | |||
3293 | // For anonymous fields, match up by index. | |||
3294 | if (!Name && | |||
3295 | ASTImporter::getFieldIndex(D) != | |||
3296 | ASTImporter::getFieldIndex(FoundField)) | |||
3297 | continue; | |||
3298 | ||||
3299 | if (Importer.IsStructurallyEquivalent(D->getType(), | |||
3300 | FoundField->getType())) { | |||
3301 | Importer.MapImported(D, FoundField); | |||
3302 | // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the | |||
3303 | // initializer of a FieldDecl might not had been instantiated in the | |||
3304 | // "To" context. However, the "From" context might instantiated that, | |||
3305 | // thus we have to merge that. | |||
3306 | if (Expr *FromInitializer = D->getInClassInitializer()) { | |||
3307 | // We don't have yet the initializer set. | |||
3308 | if (FoundField->hasInClassInitializer() && | |||
3309 | !FoundField->getInClassInitializer()) { | |||
3310 | if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) | |||
3311 | FoundField->setInClassInitializer(*ToInitializerOrErr); | |||
3312 | else { | |||
3313 | // We can't return error here, | |||
3314 | // since we already mapped D as imported. | |||
3315 | // FIXME: warning message? | |||
3316 | consumeError(ToInitializerOrErr.takeError()); | |||
3317 | return FoundField; | |||
3318 | } | |||
3319 | } | |||
3320 | } | |||
3321 | return FoundField; | |||
3322 | } | |||
3323 | ||||
3324 | // FIXME: Why is this case not handled with calling HandleNameConflict? | |||
3325 | Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) | |||
3326 | << Name << D->getType() << FoundField->getType(); | |||
3327 | Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) | |||
3328 | << FoundField->getType(); | |||
3329 | ||||
3330 | return make_error<ImportError>(ImportError::NameConflict); | |||
3331 | } | |||
3332 | } | |||
3333 | ||||
3334 | QualType ToType; | |||
3335 | TypeSourceInfo *ToTInfo; | |||
3336 | Expr *ToBitWidth; | |||
3337 | SourceLocation ToInnerLocStart; | |||
3338 | Expr *ToInitializer; | |||
3339 | if (auto Imp = importSeq( | |||
3340 | D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), | |||
3341 | D->getInnerLocStart(), D->getInClassInitializer())) | |||
3342 | std::tie( | |||
3343 | ToType, ToTInfo, ToBitWidth, ToInnerLocStart, ToInitializer) = *Imp; | |||
3344 | else | |||
3345 | return Imp.takeError(); | |||
3346 | ||||
3347 | FieldDecl *ToField; | |||
3348 | if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC, | |||
3349 | ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), | |||
3350 | ToType, ToTInfo, ToBitWidth, D->isMutable(), | |||
3351 | D->getInClassInitStyle())) | |||
3352 | return ToField; | |||
3353 | ||||
3354 | ToField->setAccess(D->getAccess()); | |||
3355 | ToField->setLexicalDeclContext(LexicalDC); | |||
3356 | if (ToInitializer) | |||
3357 | ToField->setInClassInitializer(ToInitializer); | |||
3358 | ToField->setImplicit(D->isImplicit()); | |||
3359 | LexicalDC->addDeclInternal(ToField); | |||
3360 | return ToField; | |||
3361 | } | |||
3362 | ||||
3363 | ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) { | |||
3364 | // Import the major distinguishing characteristics of a variable. | |||
3365 | DeclContext *DC, *LexicalDC; | |||
3366 | DeclarationName Name; | |||
3367 | SourceLocation Loc; | |||
3368 | NamedDecl *ToD; | |||
3369 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
3370 | return std::move(Err); | |||
3371 | if (ToD) | |||
3372 | return ToD; | |||
3373 | ||||
3374 | // Determine whether we've already imported this field. | |||
3375 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
3376 | for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { | |||
3377 | if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) { | |||
3378 | // For anonymous indirect fields, match up by index. | |||
3379 | if (!Name && | |||
3380 | ASTImporter::getFieldIndex(D) != | |||
3381 | ASTImporter::getFieldIndex(FoundField)) | |||
3382 | continue; | |||
3383 | ||||
3384 | if (Importer.IsStructurallyEquivalent(D->getType(), | |||
3385 | FoundField->getType(), | |||
3386 | !Name.isEmpty())) { | |||
3387 | Importer.MapImported(D, FoundField); | |||
3388 | return FoundField; | |||
3389 | } | |||
3390 | ||||
3391 | // If there are more anonymous fields to check, continue. | |||
3392 | if (!Name && I < N-1) | |||
3393 | continue; | |||
3394 | ||||
3395 | // FIXME: Why is this case not handled with calling HandleNameConflict? | |||
3396 | Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) | |||
3397 | << Name << D->getType() << FoundField->getType(); | |||
3398 | Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) | |||
3399 | << FoundField->getType(); | |||
3400 | ||||
3401 | return make_error<ImportError>(ImportError::NameConflict); | |||
3402 | } | |||
3403 | } | |||
3404 | ||||
3405 | // Import the type. | |||
3406 | auto TypeOrErr = import(D->getType()); | |||
3407 | if (!TypeOrErr) | |||
3408 | return TypeOrErr.takeError(); | |||
3409 | ||||
3410 | auto **NamedChain = | |||
3411 | new (Importer.getToContext()) NamedDecl*[D->getChainingSize()]; | |||
3412 | ||||
3413 | unsigned i = 0; | |||
3414 | for (auto *PI : D->chain()) | |||
3415 | if (Expected<NamedDecl *> ToD = import(PI)) | |||
3416 | NamedChain[i++] = *ToD; | |||
3417 | else | |||
3418 | return ToD.takeError(); | |||
3419 | ||||
3420 | llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()}; | |||
3421 | IndirectFieldDecl *ToIndirectField; | |||
3422 | if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC, | |||
3423 | Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH)) | |||
3424 | // FIXME here we leak `NamedChain` which is allocated before | |||
3425 | return ToIndirectField; | |||
3426 | ||||
3427 | ToIndirectField->setAccess(D->getAccess()); | |||
3428 | ToIndirectField->setLexicalDeclContext(LexicalDC); | |||
3429 | LexicalDC->addDeclInternal(ToIndirectField); | |||
3430 | return ToIndirectField; | |||
3431 | } | |||
3432 | ||||
3433 | ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) { | |||
3434 | // Import the major distinguishing characteristics of a declaration. | |||
3435 | DeclContext *DC, *LexicalDC; | |||
3436 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
3437 | return std::move(Err); | |||
3438 | ||||
3439 | // Determine whether we've already imported this decl. | |||
3440 | // FriendDecl is not a NamedDecl so we cannot use lookup. | |||
3441 | auto *RD = cast<CXXRecordDecl>(DC); | |||
3442 | FriendDecl *ImportedFriend = RD->getFirstFriend(); | |||
3443 | ||||
3444 | while (ImportedFriend) { | |||
3445 | if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) { | |||
3446 | if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(), | |||
3447 | /*Complain=*/false)) | |||
3448 | return Importer.MapImported(D, ImportedFriend); | |||
3449 | ||||
3450 | } else if (D->getFriendType() && ImportedFriend->getFriendType()) { | |||
3451 | if (Importer.IsStructurallyEquivalent( | |||
3452 | D->getFriendType()->getType(), | |||
3453 | ImportedFriend->getFriendType()->getType(), true)) | |||
3454 | return Importer.MapImported(D, ImportedFriend); | |||
3455 | } | |||
3456 | ImportedFriend = ImportedFriend->getNextFriend(); | |||
3457 | } | |||
3458 | ||||
3459 | // Not found. Create it. | |||
3460 | FriendDecl::FriendUnion ToFU; | |||
3461 | if (NamedDecl *FriendD = D->getFriendDecl()) { | |||
3462 | NamedDecl *ToFriendD; | |||
3463 | if (Error Err = importInto(ToFriendD, FriendD)) | |||
3464 | return std::move(Err); | |||
3465 | ||||
3466 | if (FriendD->getFriendObjectKind() != Decl::FOK_None && | |||
3467 | !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator))) | |||
3468 | ToFriendD->setObjectOfFriendDecl(false); | |||
3469 | ||||
3470 | ToFU = ToFriendD; | |||
3471 | } else { // The friend is a type, not a decl. | |||
3472 | if (auto TSIOrErr = import(D->getFriendType())) | |||
3473 | ToFU = *TSIOrErr; | |||
3474 | else | |||
3475 | return TSIOrErr.takeError(); | |||
3476 | } | |||
3477 | ||||
3478 | SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists); | |||
3479 | auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>(); | |||
3480 | for (unsigned I = 0; I < D->NumTPLists; I++) { | |||
3481 | if (auto ListOrErr = import(FromTPLists[I])) | |||
3482 | ToTPLists[I] = *ListOrErr; | |||
3483 | else | |||
3484 | return ListOrErr.takeError(); | |||
3485 | } | |||
3486 | ||||
3487 | auto LocationOrErr = import(D->getLocation()); | |||
3488 | if (!LocationOrErr) | |||
3489 | return LocationOrErr.takeError(); | |||
3490 | auto FriendLocOrErr = import(D->getFriendLoc()); | |||
3491 | if (!FriendLocOrErr) | |||
3492 | return FriendLocOrErr.takeError(); | |||
3493 | ||||
3494 | FriendDecl *FrD; | |||
3495 | if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC, | |||
3496 | *LocationOrErr, ToFU, | |||
3497 | *FriendLocOrErr, ToTPLists)) | |||
3498 | return FrD; | |||
3499 | ||||
3500 | FrD->setAccess(D->getAccess()); | |||
3501 | FrD->setLexicalDeclContext(LexicalDC); | |||
3502 | LexicalDC->addDeclInternal(FrD); | |||
3503 | return FrD; | |||
3504 | } | |||
3505 | ||||
3506 | ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) { | |||
3507 | // Import the major distinguishing characteristics of an ivar. | |||
3508 | DeclContext *DC, *LexicalDC; | |||
3509 | DeclarationName Name; | |||
3510 | SourceLocation Loc; | |||
3511 | NamedDecl *ToD; | |||
3512 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
3513 | return std::move(Err); | |||
3514 | if (ToD) | |||
3515 | return ToD; | |||
3516 | ||||
3517 | // Determine whether we've already imported this ivar | |||
3518 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
3519 | for (auto *FoundDecl : FoundDecls) { | |||
3520 | if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) { | |||
3521 | if (Importer.IsStructurallyEquivalent(D->getType(), | |||
3522 | FoundIvar->getType())) { | |||
3523 | Importer.MapImported(D, FoundIvar); | |||
3524 | return FoundIvar; | |||
3525 | } | |||
3526 | ||||
3527 | Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent) | |||
3528 | << Name << D->getType() << FoundIvar->getType(); | |||
3529 | Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here) | |||
3530 | << FoundIvar->getType(); | |||
3531 | ||||
3532 | return make_error<ImportError>(ImportError::NameConflict); | |||
3533 | } | |||
3534 | } | |||
3535 | ||||
3536 | QualType ToType; | |||
3537 | TypeSourceInfo *ToTypeSourceInfo; | |||
3538 | Expr *ToBitWidth; | |||
3539 | SourceLocation ToInnerLocStart; | |||
3540 | if (auto Imp = importSeq( | |||
3541 | D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), D->getInnerLocStart())) | |||
3542 | std::tie(ToType, ToTypeSourceInfo, ToBitWidth, ToInnerLocStart) = *Imp; | |||
3543 | else | |||
3544 | return Imp.takeError(); | |||
3545 | ||||
3546 | ObjCIvarDecl *ToIvar; | |||
3547 | if (GetImportedOrCreateDecl( | |||
3548 | ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC), | |||
3549 | ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), | |||
3550 | ToType, ToTypeSourceInfo, | |||
3551 | D->getAccessControl(),ToBitWidth, D->getSynthesize())) | |||
3552 | return ToIvar; | |||
3553 | ||||
3554 | ToIvar->setLexicalDeclContext(LexicalDC); | |||
3555 | LexicalDC->addDeclInternal(ToIvar); | |||
3556 | return ToIvar; | |||
3557 | } | |||
3558 | ||||
3559 | ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) { | |||
3560 | ||||
3561 | SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D); | |||
3562 | auto RedeclIt = Redecls.begin(); | |||
3563 | // Import the first part of the decl chain. I.e. import all previous | |||
3564 | // declarations starting from the canonical decl. | |||
3565 | for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { | |||
3566 | ExpectedDecl RedeclOrErr = import(*RedeclIt); | |||
3567 | if (!RedeclOrErr) | |||
3568 | return RedeclOrErr.takeError(); | |||
3569 | } | |||
3570 | assert(*RedeclIt == D)((*RedeclIt == D) ? static_cast<void> (0) : __assert_fail ("*RedeclIt == D", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 3570, __PRETTY_FUNCTION__)); | |||
3571 | ||||
3572 | // Import the major distinguishing characteristics of a variable. | |||
3573 | DeclContext *DC, *LexicalDC; | |||
3574 | DeclarationName Name; | |||
3575 | SourceLocation Loc; | |||
3576 | NamedDecl *ToD; | |||
3577 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
3578 | return std::move(Err); | |||
3579 | if (ToD) | |||
3580 | return ToD; | |||
3581 | ||||
3582 | // Try to find a variable in our own ("to") context with the same name and | |||
3583 | // in the same context as the variable we're importing. | |||
3584 | VarDecl *FoundByLookup = nullptr; | |||
3585 | if (D->isFileVarDecl()) { | |||
3586 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
3587 | unsigned IDNS = Decl::IDNS_Ordinary; | |||
3588 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
3589 | for (auto *FoundDecl : FoundDecls) { | |||
3590 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
3591 | continue; | |||
3592 | ||||
3593 | if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) { | |||
3594 | if (!hasSameVisibilityContext(FoundVar, D)) | |||
3595 | continue; | |||
3596 | if (Importer.IsStructurallyEquivalent(D->getType(), | |||
3597 | FoundVar->getType())) { | |||
3598 | ||||
3599 | // The VarDecl in the "From" context has a definition, but in the | |||
3600 | // "To" context we already have a definition. | |||
3601 | VarDecl *FoundDef = FoundVar->getDefinition(); | |||
3602 | if (D->isThisDeclarationADefinition() && FoundDef) | |||
3603 | // FIXME Check for ODR error if the two definitions have | |||
3604 | // different initializers? | |||
3605 | return Importer.MapImported(D, FoundDef); | |||
3606 | ||||
3607 | // The VarDecl in the "From" context has an initializer, but in the | |||
3608 | // "To" context we already have an initializer. | |||
3609 | const VarDecl *FoundDInit = nullptr; | |||
3610 | if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit)) | |||
3611 | // FIXME Diagnose ODR error if the two initializers are different? | |||
3612 | return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit)); | |||
3613 | ||||
3614 | FoundByLookup = FoundVar; | |||
3615 | break; | |||
3616 | } | |||
3617 | ||||
3618 | const ArrayType *FoundArray | |||
3619 | = Importer.getToContext().getAsArrayType(FoundVar->getType()); | |||
3620 | const ArrayType *TArray | |||
3621 | = Importer.getToContext().getAsArrayType(D->getType()); | |||
3622 | if (FoundArray && TArray) { | |||
3623 | if (isa<IncompleteArrayType>(FoundArray) && | |||
3624 | isa<ConstantArrayType>(TArray)) { | |||
3625 | // Import the type. | |||
3626 | if (auto TyOrErr = import(D->getType())) | |||
3627 | FoundVar->setType(*TyOrErr); | |||
3628 | else | |||
3629 | return TyOrErr.takeError(); | |||
3630 | ||||
3631 | FoundByLookup = FoundVar; | |||
3632 | break; | |||
3633 | } else if (isa<IncompleteArrayType>(TArray) && | |||
3634 | isa<ConstantArrayType>(FoundArray)) { | |||
3635 | FoundByLookup = FoundVar; | |||
3636 | break; | |||
3637 | } | |||
3638 | } | |||
3639 | ||||
3640 | Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent) | |||
3641 | << Name << D->getType() << FoundVar->getType(); | |||
3642 | Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here) | |||
3643 | << FoundVar->getType(); | |||
3644 | } | |||
3645 | ||||
3646 | ConflictingDecls.push_back(FoundDecl); | |||
3647 | } | |||
3648 | ||||
3649 | if (!ConflictingDecls.empty()) { | |||
3650 | Name = Importer.HandleNameConflict(Name, DC, IDNS, | |||
3651 | ConflictingDecls.data(), | |||
3652 | ConflictingDecls.size()); | |||
3653 | if (!Name) | |||
3654 | return make_error<ImportError>(ImportError::NameConflict); | |||
3655 | } | |||
3656 | } | |||
3657 | ||||
3658 | QualType ToType; | |||
3659 | TypeSourceInfo *ToTypeSourceInfo; | |||
3660 | SourceLocation ToInnerLocStart; | |||
3661 | NestedNameSpecifierLoc ToQualifierLoc; | |||
3662 | if (auto Imp = importSeq( | |||
3663 | D->getType(), D->getTypeSourceInfo(), D->getInnerLocStart(), | |||
3664 | D->getQualifierLoc())) | |||
3665 | std::tie(ToType, ToTypeSourceInfo, ToInnerLocStart, ToQualifierLoc) = *Imp; | |||
3666 | else | |||
3667 | return Imp.takeError(); | |||
3668 | ||||
3669 | // Create the imported variable. | |||
3670 | VarDecl *ToVar; | |||
3671 | if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC, | |||
3672 | ToInnerLocStart, Loc, | |||
3673 | Name.getAsIdentifierInfo(), | |||
3674 | ToType, ToTypeSourceInfo, | |||
3675 | D->getStorageClass())) | |||
3676 | return ToVar; | |||
3677 | ||||
3678 | ToVar->setQualifierInfo(ToQualifierLoc); | |||
3679 | ToVar->setAccess(D->getAccess()); | |||
3680 | ToVar->setLexicalDeclContext(LexicalDC); | |||
3681 | ||||
3682 | if (FoundByLookup) { | |||
3683 | auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl()); | |||
3684 | ToVar->setPreviousDecl(Recent); | |||
3685 | } | |||
3686 | ||||
3687 | if (Error Err = ImportInitializer(D, ToVar)) | |||
3688 | return std::move(Err); | |||
3689 | ||||
3690 | if (D->isConstexpr()) | |||
3691 | ToVar->setConstexpr(true); | |||
3692 | ||||
3693 | if (D->getDeclContext()->containsDeclAndLoad(D)) | |||
3694 | DC->addDeclInternal(ToVar); | |||
3695 | if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D)) | |||
3696 | LexicalDC->addDeclInternal(ToVar); | |||
3697 | ||||
3698 | // Import the rest of the chain. I.e. import all subsequent declarations. | |||
3699 | for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { | |||
3700 | ExpectedDecl RedeclOrErr = import(*RedeclIt); | |||
3701 | if (!RedeclOrErr) | |||
3702 | return RedeclOrErr.takeError(); | |||
3703 | } | |||
3704 | ||||
3705 | return ToVar; | |||
3706 | } | |||
3707 | ||||
3708 | ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { | |||
3709 | // Parameters are created in the translation unit's context, then moved | |||
3710 | // into the function declaration's context afterward. | |||
3711 | DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); | |||
3712 | ||||
3713 | DeclarationName ToDeclName; | |||
3714 | SourceLocation ToLocation; | |||
3715 | QualType ToType; | |||
3716 | if (auto Imp = importSeq(D->getDeclName(), D->getLocation(), D->getType())) | |||
3717 | std::tie(ToDeclName, ToLocation, ToType) = *Imp; | |||
3718 | else | |||
3719 | return Imp.takeError(); | |||
3720 | ||||
3721 | // Create the imported parameter. | |||
3722 | ImplicitParamDecl *ToParm = nullptr; | |||
3723 | if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, | |||
3724 | ToLocation, ToDeclName.getAsIdentifierInfo(), | |||
3725 | ToType, D->getParameterKind())) | |||
3726 | return ToParm; | |||
3727 | return ToParm; | |||
3728 | } | |||
3729 | ||||
3730 | ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { | |||
3731 | // Parameters are created in the translation unit's context, then moved | |||
3732 | // into the function declaration's context afterward. | |||
3733 | DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); | |||
3734 | ||||
3735 | DeclarationName ToDeclName; | |||
3736 | SourceLocation ToLocation, ToInnerLocStart; | |||
3737 | QualType ToType; | |||
3738 | TypeSourceInfo *ToTypeSourceInfo; | |||
3739 | if (auto Imp = importSeq( | |||
3740 | D->getDeclName(), D->getLocation(), D->getType(), D->getInnerLocStart(), | |||
3741 | D->getTypeSourceInfo())) | |||
3742 | std::tie( | |||
3743 | ToDeclName, ToLocation, ToType, ToInnerLocStart, | |||
3744 | ToTypeSourceInfo) = *Imp; | |||
3745 | else | |||
3746 | return Imp.takeError(); | |||
3747 | ||||
3748 | ParmVarDecl *ToParm; | |||
3749 | if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, | |||
3750 | ToInnerLocStart, ToLocation, | |||
3751 | ToDeclName.getAsIdentifierInfo(), ToType, | |||
3752 | ToTypeSourceInfo, D->getStorageClass(), | |||
3753 | /*DefaultArg*/ nullptr)) | |||
3754 | return ToParm; | |||
3755 | ||||
3756 | // Set the default argument. | |||
3757 | ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg()); | |||
3758 | ToParm->setKNRPromoted(D->isKNRPromoted()); | |||
3759 | ||||
3760 | if (D->hasUninstantiatedDefaultArg()) { | |||
3761 | if (auto ToDefArgOrErr = import(D->getUninstantiatedDefaultArg())) | |||
3762 | ToParm->setUninstantiatedDefaultArg(*ToDefArgOrErr); | |||
3763 | else | |||
3764 | return ToDefArgOrErr.takeError(); | |||
3765 | } else if (D->hasUnparsedDefaultArg()) { | |||
3766 | ToParm->setUnparsedDefaultArg(); | |||
3767 | } else if (D->hasDefaultArg()) { | |||
3768 | if (auto ToDefArgOrErr = import(D->getDefaultArg())) | |||
3769 | ToParm->setDefaultArg(*ToDefArgOrErr); | |||
3770 | else | |||
3771 | return ToDefArgOrErr.takeError(); | |||
3772 | } | |||
3773 | ||||
3774 | if (D->isObjCMethodParameter()) { | |||
3775 | ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex()); | |||
3776 | ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier()); | |||
3777 | } else { | |||
3778 | ToParm->setScopeInfo(D->getFunctionScopeDepth(), | |||
3779 | D->getFunctionScopeIndex()); | |||
3780 | } | |||
3781 | ||||
3782 | return ToParm; | |||
3783 | } | |||
3784 | ||||
3785 | ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { | |||
3786 | // Import the major distinguishing characteristics of a method. | |||
3787 | DeclContext *DC, *LexicalDC; | |||
3788 | DeclarationName Name; | |||
3789 | SourceLocation Loc; | |||
3790 | NamedDecl *ToD; | |||
3791 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
3792 | return std::move(Err); | |||
3793 | if (ToD) | |||
3794 | return ToD; | |||
3795 | ||||
3796 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
3797 | for (auto *FoundDecl : FoundDecls) { | |||
3798 | if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) { | |||
3799 | if (FoundMethod->isInstanceMethod() != D->isInstanceMethod()) | |||
3800 | continue; | |||
3801 | ||||
3802 | // Check return types. | |||
3803 | if (!Importer.IsStructurallyEquivalent(D->getReturnType(), | |||
3804 | FoundMethod->getReturnType())) { | |||
3805 | Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent) | |||
3806 | << D->isInstanceMethod() << Name << D->getReturnType() | |||
3807 | << FoundMethod->getReturnType(); | |||
3808 | Importer.ToDiag(FoundMethod->getLocation(), | |||
3809 | diag::note_odr_objc_method_here) | |||
3810 | << D->isInstanceMethod() << Name; | |||
3811 | ||||
3812 | return make_error<ImportError>(ImportError::NameConflict); | |||
3813 | } | |||
3814 | ||||
3815 | // Check the number of parameters. | |||
3816 | if (D->param_size() != FoundMethod->param_size()) { | |||
3817 | Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent) | |||
3818 | << D->isInstanceMethod() << Name | |||
3819 | << D->param_size() << FoundMethod->param_size(); | |||
3820 | Importer.ToDiag(FoundMethod->getLocation(), | |||
3821 | diag::note_odr_objc_method_here) | |||
3822 | << D->isInstanceMethod() << Name; | |||
3823 | ||||
3824 | return make_error<ImportError>(ImportError::NameConflict); | |||
3825 | } | |||
3826 | ||||
3827 | // Check parameter types. | |||
3828 | for (ObjCMethodDecl::param_iterator P = D->param_begin(), | |||
3829 | PEnd = D->param_end(), FoundP = FoundMethod->param_begin(); | |||
3830 | P != PEnd; ++P, ++FoundP) { | |||
3831 | if (!Importer.IsStructurallyEquivalent((*P)->getType(), | |||
3832 | (*FoundP)->getType())) { | |||
3833 | Importer.FromDiag((*P)->getLocation(), | |||
3834 | diag::warn_odr_objc_method_param_type_inconsistent) | |||
3835 | << D->isInstanceMethod() << Name | |||
3836 | << (*P)->getType() << (*FoundP)->getType(); | |||
3837 | Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here) | |||
3838 | << (*FoundP)->getType(); | |||
3839 | ||||
3840 | return make_error<ImportError>(ImportError::NameConflict); | |||
3841 | } | |||
3842 | } | |||
3843 | ||||
3844 | // Check variadic/non-variadic. | |||
3845 | // Check the number of parameters. | |||
3846 | if (D->isVariadic() != FoundMethod->isVariadic()) { | |||
3847 | Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent) | |||
3848 | << D->isInstanceMethod() << Name; | |||
3849 | Importer.ToDiag(FoundMethod->getLocation(), | |||
3850 | diag::note_odr_objc_method_here) | |||
3851 | << D->isInstanceMethod() << Name; | |||
3852 | ||||
3853 | return make_error<ImportError>(ImportError::NameConflict); | |||
3854 | } | |||
3855 | ||||
3856 | // FIXME: Any other bits we need to merge? | |||
3857 | return Importer.MapImported(D, FoundMethod); | |||
3858 | } | |||
3859 | } | |||
3860 | ||||
3861 | SourceLocation ToEndLoc; | |||
3862 | QualType ToReturnType; | |||
3863 | TypeSourceInfo *ToReturnTypeSourceInfo; | |||
3864 | if (auto Imp = importSeq( | |||
3865 | D->getEndLoc(), D->getReturnType(), D->getReturnTypeSourceInfo())) | |||
3866 | std::tie(ToEndLoc, ToReturnType, ToReturnTypeSourceInfo) = *Imp; | |||
3867 | else | |||
3868 | return Imp.takeError(); | |||
3869 | ||||
3870 | ObjCMethodDecl *ToMethod; | |||
3871 | if (GetImportedOrCreateDecl( | |||
3872 | ToMethod, D, Importer.getToContext(), Loc, | |||
3873 | ToEndLoc, Name.getObjCSelector(), ToReturnType, | |||
3874 | ToReturnTypeSourceInfo, DC, D->isInstanceMethod(), D->isVariadic(), | |||
3875 | D->isPropertyAccessor(), D->isImplicit(), D->isDefined(), | |||
3876 | D->getImplementationControl(), D->hasRelatedResultType())) | |||
3877 | return ToMethod; | |||
3878 | ||||
3879 | // FIXME: When we decide to merge method definitions, we'll need to | |||
3880 | // deal with implicit parameters. | |||
3881 | ||||
3882 | // Import the parameters | |||
3883 | SmallVector<ParmVarDecl *, 5> ToParams; | |||
3884 | for (auto *FromP : D->parameters()) { | |||
3885 | if (Expected<ParmVarDecl *> ToPOrErr = import(FromP)) | |||
3886 | ToParams.push_back(*ToPOrErr); | |||
3887 | else | |||
3888 | return ToPOrErr.takeError(); | |||
3889 | } | |||
3890 | ||||
3891 | // Set the parameters. | |||
3892 | for (auto *ToParam : ToParams) { | |||
3893 | ToParam->setOwningFunction(ToMethod); | |||
3894 | ToMethod->addDeclInternal(ToParam); | |||
3895 | } | |||
3896 | ||||
3897 | SmallVector<SourceLocation, 12> FromSelLocs; | |||
3898 | D->getSelectorLocs(FromSelLocs); | |||
3899 | SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size()); | |||
3900 | if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs)) | |||
3901 | return std::move(Err); | |||
3902 | ||||
3903 | ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs); | |||
3904 | ||||
3905 | ToMethod->setLexicalDeclContext(LexicalDC); | |||
3906 | LexicalDC->addDeclInternal(ToMethod); | |||
3907 | return ToMethod; | |||
3908 | } | |||
3909 | ||||
3910 | ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { | |||
3911 | // Import the major distinguishing characteristics of a category. | |||
3912 | DeclContext *DC, *LexicalDC; | |||
3913 | DeclarationName Name; | |||
3914 | SourceLocation Loc; | |||
3915 | NamedDecl *ToD; | |||
3916 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
3917 | return std::move(Err); | |||
3918 | if (ToD) | |||
3919 | return ToD; | |||
3920 | ||||
3921 | SourceLocation ToVarianceLoc, ToLocation, ToColonLoc; | |||
3922 | TypeSourceInfo *ToTypeSourceInfo; | |||
3923 | if (auto Imp = importSeq( | |||
3924 | D->getVarianceLoc(), D->getLocation(), D->getColonLoc(), | |||
3925 | D->getTypeSourceInfo())) | |||
3926 | std::tie(ToVarianceLoc, ToLocation, ToColonLoc, ToTypeSourceInfo) = *Imp; | |||
3927 | else | |||
3928 | return Imp.takeError(); | |||
3929 | ||||
3930 | ObjCTypeParamDecl *Result; | |||
3931 | if (GetImportedOrCreateDecl( | |||
3932 | Result, D, Importer.getToContext(), DC, D->getVariance(), | |||
3933 | ToVarianceLoc, D->getIndex(), | |||
3934 | ToLocation, Name.getAsIdentifierInfo(), | |||
3935 | ToColonLoc, ToTypeSourceInfo)) | |||
3936 | return Result; | |||
3937 | ||||
3938 | Result->setLexicalDeclContext(LexicalDC); | |||
3939 | return Result; | |||
3940 | } | |||
3941 | ||||
3942 | ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { | |||
3943 | // Import the major distinguishing characteristics of a category. | |||
3944 | DeclContext *DC, *LexicalDC; | |||
3945 | DeclarationName Name; | |||
3946 | SourceLocation Loc; | |||
3947 | NamedDecl *ToD; | |||
3948 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
3949 | return std::move(Err); | |||
3950 | if (ToD) | |||
3951 | return ToD; | |||
3952 | ||||
3953 | ObjCInterfaceDecl *ToInterface; | |||
3954 | if (Error Err = importInto(ToInterface, D->getClassInterface())) | |||
3955 | return std::move(Err); | |||
3956 | ||||
3957 | // Determine if we've already encountered this category. | |||
3958 | ObjCCategoryDecl *MergeWithCategory | |||
3959 | = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo()); | |||
3960 | ObjCCategoryDecl *ToCategory = MergeWithCategory; | |||
3961 | if (!ToCategory) { | |||
3962 | SourceLocation ToAtStartLoc, ToCategoryNameLoc; | |||
3963 | SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc; | |||
3964 | if (auto Imp = importSeq( | |||
3965 | D->getAtStartLoc(), D->getCategoryNameLoc(), | |||
3966 | D->getIvarLBraceLoc(), D->getIvarRBraceLoc())) | |||
3967 | std::tie( | |||
3968 | ToAtStartLoc, ToCategoryNameLoc, | |||
3969 | ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp; | |||
3970 | else | |||
3971 | return Imp.takeError(); | |||
3972 | ||||
3973 | if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC, | |||
3974 | ToAtStartLoc, Loc, | |||
3975 | ToCategoryNameLoc, | |||
3976 | Name.getAsIdentifierInfo(), ToInterface, | |||
3977 | /*TypeParamList=*/nullptr, | |||
3978 | ToIvarLBraceLoc, | |||
3979 | ToIvarRBraceLoc)) | |||
3980 | return ToCategory; | |||
3981 | ||||
3982 | ToCategory->setLexicalDeclContext(LexicalDC); | |||
3983 | LexicalDC->addDeclInternal(ToCategory); | |||
3984 | // Import the type parameter list after MapImported, to avoid | |||
3985 | // loops when bringing in their DeclContext. | |||
3986 | if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList())) | |||
3987 | ToCategory->setTypeParamList(*PListOrErr); | |||
3988 | else | |||
3989 | return PListOrErr.takeError(); | |||
3990 | ||||
3991 | // Import protocols | |||
3992 | SmallVector<ObjCProtocolDecl *, 4> Protocols; | |||
3993 | SmallVector<SourceLocation, 4> ProtocolLocs; | |||
3994 | ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc | |||
3995 | = D->protocol_loc_begin(); | |||
3996 | for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(), | |||
3997 | FromProtoEnd = D->protocol_end(); | |||
3998 | FromProto != FromProtoEnd; | |||
3999 | ++FromProto, ++FromProtoLoc) { | |||
4000 | if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) | |||
4001 | Protocols.push_back(*ToProtoOrErr); | |||
4002 | else | |||
4003 | return ToProtoOrErr.takeError(); | |||
4004 | ||||
4005 | if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) | |||
4006 | ProtocolLocs.push_back(*ToProtoLocOrErr); | |||
4007 | else | |||
4008 | return ToProtoLocOrErr.takeError(); | |||
4009 | } | |||
4010 | ||||
4011 | // FIXME: If we're merging, make sure that the protocol list is the same. | |||
4012 | ToCategory->setProtocolList(Protocols.data(), Protocols.size(), | |||
4013 | ProtocolLocs.data(), Importer.getToContext()); | |||
4014 | ||||
4015 | } else { | |||
4016 | Importer.MapImported(D, ToCategory); | |||
4017 | } | |||
4018 | ||||
4019 | // Import all of the members of this category. | |||
4020 | if (Error Err = ImportDeclContext(D)) | |||
4021 | return std::move(Err); | |||
4022 | ||||
4023 | // If we have an implementation, import it as well. | |||
4024 | if (D->getImplementation()) { | |||
4025 | if (Expected<ObjCCategoryImplDecl *> ToImplOrErr = | |||
4026 | import(D->getImplementation())) | |||
4027 | ToCategory->setImplementation(*ToImplOrErr); | |||
4028 | else | |||
4029 | return ToImplOrErr.takeError(); | |||
4030 | } | |||
4031 | ||||
4032 | return ToCategory; | |||
4033 | } | |||
4034 | ||||
4035 | Error ASTNodeImporter::ImportDefinition( | |||
4036 | ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { | |||
4037 | if (To->getDefinition()) { | |||
4038 | if (shouldForceImportDeclContext(Kind)) | |||
4039 | if (Error Err = ImportDeclContext(From)) | |||
4040 | return Err; | |||
4041 | return Error::success(); | |||
4042 | } | |||
4043 | ||||
4044 | // Start the protocol definition | |||
4045 | To->startDefinition(); | |||
4046 | ||||
4047 | // Import protocols | |||
4048 | SmallVector<ObjCProtocolDecl *, 4> Protocols; | |||
4049 | SmallVector<SourceLocation, 4> ProtocolLocs; | |||
4050 | ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = | |||
4051 | From->protocol_loc_begin(); | |||
4052 | for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), | |||
4053 | FromProtoEnd = From->protocol_end(); | |||
4054 | FromProto != FromProtoEnd; | |||
4055 | ++FromProto, ++FromProtoLoc) { | |||
4056 | if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) | |||
4057 | Protocols.push_back(*ToProtoOrErr); | |||
4058 | else | |||
4059 | return ToProtoOrErr.takeError(); | |||
4060 | ||||
4061 | if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) | |||
4062 | ProtocolLocs.push_back(*ToProtoLocOrErr); | |||
4063 | else | |||
4064 | return ToProtoLocOrErr.takeError(); | |||
4065 | ||||
4066 | } | |||
4067 | ||||
4068 | // FIXME: If we're merging, make sure that the protocol list is the same. | |||
4069 | To->setProtocolList(Protocols.data(), Protocols.size(), | |||
4070 | ProtocolLocs.data(), Importer.getToContext()); | |||
4071 | ||||
4072 | if (shouldForceImportDeclContext(Kind)) { | |||
4073 | // Import all of the members of this protocol. | |||
4074 | if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) | |||
4075 | return Err; | |||
4076 | } | |||
4077 | return Error::success(); | |||
4078 | } | |||
4079 | ||||
4080 | ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { | |||
4081 | // If this protocol has a definition in the translation unit we're coming | |||
4082 | // from, but this particular declaration is not that definition, import the | |||
4083 | // definition and map to that. | |||
4084 | ObjCProtocolDecl *Definition = D->getDefinition(); | |||
4085 | if (Definition && Definition != D) { | |||
4086 | if (ExpectedDecl ImportedDefOrErr = import(Definition)) | |||
4087 | return Importer.MapImported(D, *ImportedDefOrErr); | |||
4088 | else | |||
4089 | return ImportedDefOrErr.takeError(); | |||
4090 | } | |||
4091 | ||||
4092 | // Import the major distinguishing characteristics of a protocol. | |||
4093 | DeclContext *DC, *LexicalDC; | |||
4094 | DeclarationName Name; | |||
4095 | SourceLocation Loc; | |||
4096 | NamedDecl *ToD; | |||
4097 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4098 | return std::move(Err); | |||
4099 | if (ToD) | |||
4100 | return ToD; | |||
4101 | ||||
4102 | ObjCProtocolDecl *MergeWithProtocol = nullptr; | |||
4103 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
4104 | for (auto *FoundDecl : FoundDecls) { | |||
4105 | if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol)) | |||
4106 | continue; | |||
4107 | ||||
4108 | if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl))) | |||
4109 | break; | |||
4110 | } | |||
4111 | ||||
4112 | ObjCProtocolDecl *ToProto = MergeWithProtocol; | |||
4113 | if (!ToProto) { | |||
4114 | auto ToAtBeginLocOrErr = import(D->getAtStartLoc()); | |||
4115 | if (!ToAtBeginLocOrErr) | |||
4116 | return ToAtBeginLocOrErr.takeError(); | |||
4117 | ||||
4118 | if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC, | |||
4119 | Name.getAsIdentifierInfo(), Loc, | |||
4120 | *ToAtBeginLocOrErr, | |||
4121 | /*PrevDecl=*/nullptr)) | |||
4122 | return ToProto; | |||
4123 | ToProto->setLexicalDeclContext(LexicalDC); | |||
4124 | LexicalDC->addDeclInternal(ToProto); | |||
4125 | } | |||
4126 | ||||
4127 | Importer.MapImported(D, ToProto); | |||
4128 | ||||
4129 | if (D->isThisDeclarationADefinition()) | |||
4130 | if (Error Err = ImportDefinition(D, ToProto)) | |||
4131 | return std::move(Err); | |||
4132 | ||||
4133 | return ToProto; | |||
4134 | } | |||
4135 | ||||
4136 | ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { | |||
4137 | DeclContext *DC, *LexicalDC; | |||
4138 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
4139 | return std::move(Err); | |||
4140 | ||||
4141 | ExpectedSLoc ExternLocOrErr = import(D->getExternLoc()); | |||
4142 | if (!ExternLocOrErr) | |||
4143 | return ExternLocOrErr.takeError(); | |||
4144 | ||||
4145 | ExpectedSLoc LangLocOrErr = import(D->getLocation()); | |||
4146 | if (!LangLocOrErr) | |||
4147 | return LangLocOrErr.takeError(); | |||
4148 | ||||
4149 | bool HasBraces = D->hasBraces(); | |||
4150 | ||||
4151 | LinkageSpecDecl *ToLinkageSpec; | |||
4152 | if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC, | |||
4153 | *ExternLocOrErr, *LangLocOrErr, | |||
4154 | D->getLanguage(), HasBraces)) | |||
4155 | return ToLinkageSpec; | |||
4156 | ||||
4157 | if (HasBraces) { | |||
4158 | ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc()); | |||
4159 | if (!RBraceLocOrErr) | |||
4160 | return RBraceLocOrErr.takeError(); | |||
4161 | ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr); | |||
4162 | } | |||
4163 | ||||
4164 | ToLinkageSpec->setLexicalDeclContext(LexicalDC); | |||
4165 | LexicalDC->addDeclInternal(ToLinkageSpec); | |||
4166 | ||||
4167 | return ToLinkageSpec; | |||
4168 | } | |||
4169 | ||||
4170 | ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) { | |||
4171 | DeclContext *DC, *LexicalDC; | |||
4172 | DeclarationName Name; | |||
4173 | SourceLocation Loc; | |||
4174 | NamedDecl *ToD = nullptr; | |||
4175 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4176 | return std::move(Err); | |||
4177 | if (ToD) | |||
4178 | return ToD; | |||
4179 | ||||
4180 | SourceLocation ToLoc, ToUsingLoc; | |||
4181 | NestedNameSpecifierLoc ToQualifierLoc; | |||
4182 | if (auto Imp = importSeq( | |||
4183 | D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc())) | |||
4184 | std::tie(ToLoc, ToUsingLoc, ToQualifierLoc) = *Imp; | |||
4185 | else | |||
4186 | return Imp.takeError(); | |||
4187 | ||||
4188 | DeclarationNameInfo NameInfo(Name, ToLoc); | |||
4189 | if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) | |||
4190 | return std::move(Err); | |||
4191 | ||||
4192 | UsingDecl *ToUsing; | |||
4193 | if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, | |||
4194 | ToUsingLoc, ToQualifierLoc, NameInfo, | |||
4195 | D->hasTypename())) | |||
4196 | return ToUsing; | |||
4197 | ||||
4198 | ToUsing->setLexicalDeclContext(LexicalDC); | |||
4199 | LexicalDC->addDeclInternal(ToUsing); | |||
4200 | ||||
4201 | if (NamedDecl *FromPattern = | |||
4202 | Importer.getFromContext().getInstantiatedFromUsingDecl(D)) { | |||
4203 | if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern)) | |||
4204 | Importer.getToContext().setInstantiatedFromUsingDecl( | |||
4205 | ToUsing, *ToPatternOrErr); | |||
4206 | else | |||
4207 | return ToPatternOrErr.takeError(); | |||
4208 | } | |||
4209 | ||||
4210 | for (UsingShadowDecl *FromShadow : D->shadows()) { | |||
4211 | if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow)) | |||
4212 | ToUsing->addShadowDecl(*ToShadowOrErr); | |||
4213 | else | |||
4214 | // FIXME: We return error here but the definition is already created | |||
4215 | // and available with lookups. How to fix this?.. | |||
4216 | return ToShadowOrErr.takeError(); | |||
4217 | } | |||
4218 | return ToUsing; | |||
4219 | } | |||
4220 | ||||
4221 | ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) { | |||
4222 | DeclContext *DC, *LexicalDC; | |||
4223 | DeclarationName Name; | |||
4224 | SourceLocation Loc; | |||
4225 | NamedDecl *ToD = nullptr; | |||
4226 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4227 | return std::move(Err); | |||
4228 | if (ToD) | |||
4229 | return ToD; | |||
4230 | ||||
4231 | Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl()); | |||
4232 | if (!ToUsingOrErr) | |||
4233 | return ToUsingOrErr.takeError(); | |||
4234 | ||||
4235 | Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl()); | |||
4236 | if (!ToTargetOrErr) | |||
4237 | return ToTargetOrErr.takeError(); | |||
4238 | ||||
4239 | UsingShadowDecl *ToShadow; | |||
4240 | if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc, | |||
4241 | *ToUsingOrErr, *ToTargetOrErr)) | |||
4242 | return ToShadow; | |||
4243 | ||||
4244 | ToShadow->setLexicalDeclContext(LexicalDC); | |||
4245 | ToShadow->setAccess(D->getAccess()); | |||
4246 | ||||
4247 | if (UsingShadowDecl *FromPattern = | |||
4248 | Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) { | |||
4249 | if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern)) | |||
4250 | Importer.getToContext().setInstantiatedFromUsingShadowDecl( | |||
4251 | ToShadow, *ToPatternOrErr); | |||
4252 | else | |||
4253 | // FIXME: We return error here but the definition is already created | |||
4254 | // and available with lookups. How to fix this?.. | |||
4255 | return ToPatternOrErr.takeError(); | |||
4256 | } | |||
4257 | ||||
4258 | LexicalDC->addDeclInternal(ToShadow); | |||
4259 | ||||
4260 | return ToShadow; | |||
4261 | } | |||
4262 | ||||
4263 | ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { | |||
4264 | DeclContext *DC, *LexicalDC; | |||
4265 | DeclarationName Name; | |||
4266 | SourceLocation Loc; | |||
4267 | NamedDecl *ToD = nullptr; | |||
4268 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4269 | return std::move(Err); | |||
4270 | if (ToD) | |||
4271 | return ToD; | |||
4272 | ||||
4273 | auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor()); | |||
4274 | if (!ToComAncestorOrErr) | |||
4275 | return ToComAncestorOrErr.takeError(); | |||
4276 | ||||
4277 | NamespaceDecl *ToNominatedNamespace; | |||
4278 | SourceLocation ToUsingLoc, ToNamespaceKeyLocation, ToIdentLocation; | |||
4279 | NestedNameSpecifierLoc ToQualifierLoc; | |||
4280 | if (auto Imp = importSeq( | |||
4281 | D->getNominatedNamespace(), D->getUsingLoc(), | |||
4282 | D->getNamespaceKeyLocation(), D->getQualifierLoc(), | |||
4283 | D->getIdentLocation())) | |||
4284 | std::tie( | |||
4285 | ToNominatedNamespace, ToUsingLoc, ToNamespaceKeyLocation, | |||
4286 | ToQualifierLoc, ToIdentLocation) = *Imp; | |||
4287 | else | |||
4288 | return Imp.takeError(); | |||
4289 | ||||
4290 | UsingDirectiveDecl *ToUsingDir; | |||
4291 | if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC, | |||
4292 | ToUsingLoc, | |||
4293 | ToNamespaceKeyLocation, | |||
4294 | ToQualifierLoc, | |||
4295 | ToIdentLocation, | |||
4296 | ToNominatedNamespace, *ToComAncestorOrErr)) | |||
4297 | return ToUsingDir; | |||
4298 | ||||
4299 | ToUsingDir->setLexicalDeclContext(LexicalDC); | |||
4300 | LexicalDC->addDeclInternal(ToUsingDir); | |||
4301 | ||||
4302 | return ToUsingDir; | |||
4303 | } | |||
4304 | ||||
4305 | ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl( | |||
4306 | UnresolvedUsingValueDecl *D) { | |||
4307 | DeclContext *DC, *LexicalDC; | |||
4308 | DeclarationName Name; | |||
4309 | SourceLocation Loc; | |||
4310 | NamedDecl *ToD = nullptr; | |||
4311 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4312 | return std::move(Err); | |||
4313 | if (ToD) | |||
4314 | return ToD; | |||
4315 | ||||
4316 | SourceLocation ToLoc, ToUsingLoc, ToEllipsisLoc; | |||
4317 | NestedNameSpecifierLoc ToQualifierLoc; | |||
4318 | if (auto Imp = importSeq( | |||
4319 | D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc(), | |||
4320 | D->getEllipsisLoc())) | |||
4321 | std::tie(ToLoc, ToUsingLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp; | |||
4322 | else | |||
4323 | return Imp.takeError(); | |||
4324 | ||||
4325 | DeclarationNameInfo NameInfo(Name, ToLoc); | |||
4326 | if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) | |||
4327 | return std::move(Err); | |||
4328 | ||||
4329 | UnresolvedUsingValueDecl *ToUsingValue; | |||
4330 | if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC, | |||
4331 | ToUsingLoc, ToQualifierLoc, NameInfo, | |||
4332 | ToEllipsisLoc)) | |||
4333 | return ToUsingValue; | |||
4334 | ||||
4335 | ToUsingValue->setAccess(D->getAccess()); | |||
4336 | ToUsingValue->setLexicalDeclContext(LexicalDC); | |||
4337 | LexicalDC->addDeclInternal(ToUsingValue); | |||
4338 | ||||
4339 | return ToUsingValue; | |||
4340 | } | |||
4341 | ||||
4342 | ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl( | |||
4343 | UnresolvedUsingTypenameDecl *D) { | |||
4344 | DeclContext *DC, *LexicalDC; | |||
4345 | DeclarationName Name; | |||
4346 | SourceLocation Loc; | |||
4347 | NamedDecl *ToD = nullptr; | |||
4348 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4349 | return std::move(Err); | |||
4350 | if (ToD) | |||
4351 | return ToD; | |||
4352 | ||||
4353 | SourceLocation ToUsingLoc, ToTypenameLoc, ToEllipsisLoc; | |||
4354 | NestedNameSpecifierLoc ToQualifierLoc; | |||
4355 | if (auto Imp = importSeq( | |||
4356 | D->getUsingLoc(), D->getTypenameLoc(), D->getQualifierLoc(), | |||
4357 | D->getEllipsisLoc())) | |||
4358 | std::tie(ToUsingLoc, ToTypenameLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp; | |||
4359 | else | |||
4360 | return Imp.takeError(); | |||
4361 | ||||
4362 | UnresolvedUsingTypenameDecl *ToUsing; | |||
4363 | if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, | |||
4364 | ToUsingLoc, ToTypenameLoc, | |||
4365 | ToQualifierLoc, Loc, Name, ToEllipsisLoc)) | |||
4366 | return ToUsing; | |||
4367 | ||||
4368 | ToUsing->setAccess(D->getAccess()); | |||
4369 | ToUsing->setLexicalDeclContext(LexicalDC); | |||
4370 | LexicalDC->addDeclInternal(ToUsing); | |||
4371 | ||||
4372 | return ToUsing; | |||
4373 | } | |||
4374 | ||||
4375 | ||||
4376 | Error ASTNodeImporter::ImportDefinition( | |||
4377 | ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { | |||
4378 | if (To->getDefinition()) { | |||
4379 | // Check consistency of superclass. | |||
4380 | ObjCInterfaceDecl *FromSuper = From->getSuperClass(); | |||
4381 | if (FromSuper) { | |||
4382 | if (auto FromSuperOrErr = import(FromSuper)) | |||
4383 | FromSuper = *FromSuperOrErr; | |||
4384 | else | |||
4385 | return FromSuperOrErr.takeError(); | |||
4386 | } | |||
4387 | ||||
4388 | ObjCInterfaceDecl *ToSuper = To->getSuperClass(); | |||
4389 | if ((bool)FromSuper != (bool)ToSuper || | |||
4390 | (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { | |||
4391 | Importer.ToDiag(To->getLocation(), | |||
4392 | diag::warn_odr_objc_superclass_inconsistent) | |||
4393 | << To->getDeclName(); | |||
4394 | if (ToSuper) | |||
4395 | Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) | |||
4396 | << To->getSuperClass()->getDeclName(); | |||
4397 | else | |||
4398 | Importer.ToDiag(To->getLocation(), | |||
4399 | diag::note_odr_objc_missing_superclass); | |||
4400 | if (From->getSuperClass()) | |||
4401 | Importer.FromDiag(From->getSuperClassLoc(), | |||
4402 | diag::note_odr_objc_superclass) | |||
4403 | << From->getSuperClass()->getDeclName(); | |||
4404 | else | |||
4405 | Importer.FromDiag(From->getLocation(), | |||
4406 | diag::note_odr_objc_missing_superclass); | |||
4407 | } | |||
4408 | ||||
4409 | if (shouldForceImportDeclContext(Kind)) | |||
4410 | if (Error Err = ImportDeclContext(From)) | |||
4411 | return Err; | |||
4412 | return Error::success(); | |||
4413 | } | |||
4414 | ||||
4415 | // Start the definition. | |||
4416 | To->startDefinition(); | |||
4417 | ||||
4418 | // If this class has a superclass, import it. | |||
4419 | if (From->getSuperClass()) { | |||
4420 | if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo())) | |||
4421 | To->setSuperClass(*SuperTInfoOrErr); | |||
4422 | else | |||
4423 | return SuperTInfoOrErr.takeError(); | |||
4424 | } | |||
4425 | ||||
4426 | // Import protocols | |||
4427 | SmallVector<ObjCProtocolDecl *, 4> Protocols; | |||
4428 | SmallVector<SourceLocation, 4> ProtocolLocs; | |||
4429 | ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc = | |||
4430 | From->protocol_loc_begin(); | |||
4431 | ||||
4432 | for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), | |||
4433 | FromProtoEnd = From->protocol_end(); | |||
4434 | FromProto != FromProtoEnd; | |||
4435 | ++FromProto, ++FromProtoLoc) { | |||
4436 | if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) | |||
4437 | Protocols.push_back(*ToProtoOrErr); | |||
4438 | else | |||
4439 | return ToProtoOrErr.takeError(); | |||
4440 | ||||
4441 | if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) | |||
4442 | ProtocolLocs.push_back(*ToProtoLocOrErr); | |||
4443 | else | |||
4444 | return ToProtoLocOrErr.takeError(); | |||
4445 | ||||
4446 | } | |||
4447 | ||||
4448 | // FIXME: If we're merging, make sure that the protocol list is the same. | |||
4449 | To->setProtocolList(Protocols.data(), Protocols.size(), | |||
4450 | ProtocolLocs.data(), Importer.getToContext()); | |||
4451 | ||||
4452 | // Import categories. When the categories themselves are imported, they'll | |||
4453 | // hook themselves into this interface. | |||
4454 | for (auto *Cat : From->known_categories()) { | |||
4455 | auto ToCatOrErr = import(Cat); | |||
4456 | if (!ToCatOrErr) | |||
4457 | return ToCatOrErr.takeError(); | |||
4458 | } | |||
4459 | ||||
4460 | // If we have an @implementation, import it as well. | |||
4461 | if (From->getImplementation()) { | |||
4462 | if (Expected<ObjCImplementationDecl *> ToImplOrErr = | |||
4463 | import(From->getImplementation())) | |||
4464 | To->setImplementation(*ToImplOrErr); | |||
4465 | else | |||
4466 | return ToImplOrErr.takeError(); | |||
4467 | } | |||
4468 | ||||
4469 | if (shouldForceImportDeclContext(Kind)) { | |||
4470 | // Import all of the members of this class. | |||
4471 | if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) | |||
4472 | return Err; | |||
4473 | } | |||
4474 | return Error::success(); | |||
4475 | } | |||
4476 | ||||
4477 | Expected<ObjCTypeParamList *> | |||
4478 | ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) { | |||
4479 | if (!list) | |||
4480 | return nullptr; | |||
4481 | ||||
4482 | SmallVector<ObjCTypeParamDecl *, 4> toTypeParams; | |||
4483 | for (auto *fromTypeParam : *list) { | |||
4484 | if (auto toTypeParamOrErr = import(fromTypeParam)) | |||
4485 | toTypeParams.push_back(*toTypeParamOrErr); | |||
4486 | else | |||
4487 | return toTypeParamOrErr.takeError(); | |||
4488 | } | |||
4489 | ||||
4490 | auto LAngleLocOrErr = import(list->getLAngleLoc()); | |||
4491 | if (!LAngleLocOrErr) | |||
4492 | return LAngleLocOrErr.takeError(); | |||
4493 | ||||
4494 | auto RAngleLocOrErr = import(list->getRAngleLoc()); | |||
4495 | if (!RAngleLocOrErr) | |||
4496 | return RAngleLocOrErr.takeError(); | |||
4497 | ||||
4498 | return ObjCTypeParamList::create(Importer.getToContext(), | |||
4499 | *LAngleLocOrErr, | |||
4500 | toTypeParams, | |||
4501 | *RAngleLocOrErr); | |||
4502 | } | |||
4503 | ||||
4504 | ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { | |||
4505 | // If this class has a definition in the translation unit we're coming from, | |||
4506 | // but this particular declaration is not that definition, import the | |||
4507 | // definition and map to that. | |||
4508 | ObjCInterfaceDecl *Definition = D->getDefinition(); | |||
4509 | if (Definition && Definition != D) { | |||
4510 | if (ExpectedDecl ImportedDefOrErr = import(Definition)) | |||
4511 | return Importer.MapImported(D, *ImportedDefOrErr); | |||
4512 | else | |||
4513 | return ImportedDefOrErr.takeError(); | |||
4514 | } | |||
4515 | ||||
4516 | // Import the major distinguishing characteristics of an @interface. | |||
4517 | DeclContext *DC, *LexicalDC; | |||
4518 | DeclarationName Name; | |||
4519 | SourceLocation Loc; | |||
4520 | NamedDecl *ToD; | |||
4521 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4522 | return std::move(Err); | |||
4523 | if (ToD) | |||
4524 | return ToD; | |||
4525 | ||||
4526 | // Look for an existing interface with the same name. | |||
4527 | ObjCInterfaceDecl *MergeWithIface = nullptr; | |||
4528 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
4529 | for (auto *FoundDecl : FoundDecls) { | |||
4530 | if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | |||
4531 | continue; | |||
4532 | ||||
4533 | if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl))) | |||
4534 | break; | |||
4535 | } | |||
4536 | ||||
4537 | // Create an interface declaration, if one does not already exist. | |||
4538 | ObjCInterfaceDecl *ToIface = MergeWithIface; | |||
4539 | if (!ToIface) { | |||
4540 | ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc()); | |||
4541 | if (!AtBeginLocOrErr) | |||
4542 | return AtBeginLocOrErr.takeError(); | |||
4543 | ||||
4544 | if (GetImportedOrCreateDecl( | |||
4545 | ToIface, D, Importer.getToContext(), DC, | |||
4546 | *AtBeginLocOrErr, Name.getAsIdentifierInfo(), | |||
4547 | /*TypeParamList=*/nullptr, | |||
4548 | /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl())) | |||
4549 | return ToIface; | |||
4550 | ToIface->setLexicalDeclContext(LexicalDC); | |||
4551 | LexicalDC->addDeclInternal(ToIface); | |||
4552 | } | |||
4553 | Importer.MapImported(D, ToIface); | |||
4554 | // Import the type parameter list after MapImported, to avoid | |||
4555 | // loops when bringing in their DeclContext. | |||
4556 | if (auto ToPListOrErr = | |||
4557 | ImportObjCTypeParamList(D->getTypeParamListAsWritten())) | |||
4558 | ToIface->setTypeParamList(*ToPListOrErr); | |||
4559 | else | |||
4560 | return ToPListOrErr.takeError(); | |||
4561 | ||||
4562 | if (D->isThisDeclarationADefinition()) | |||
4563 | if (Error Err = ImportDefinition(D, ToIface)) | |||
4564 | return std::move(Err); | |||
4565 | ||||
4566 | return ToIface; | |||
4567 | } | |||
4568 | ||||
4569 | ExpectedDecl | |||
4570 | ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { | |||
4571 | ObjCCategoryDecl *Category; | |||
4572 | if (Error Err = importInto(Category, D->getCategoryDecl())) | |||
4573 | return std::move(Err); | |||
4574 | ||||
4575 | ObjCCategoryImplDecl *ToImpl = Category->getImplementation(); | |||
4576 | if (!ToImpl) { | |||
4577 | DeclContext *DC, *LexicalDC; | |||
4578 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
4579 | return std::move(Err); | |||
4580 | ||||
4581 | SourceLocation ToLocation, ToAtStartLoc, ToCategoryNameLoc; | |||
4582 | if (auto Imp = importSeq( | |||
4583 | D->getLocation(), D->getAtStartLoc(), D->getCategoryNameLoc())) | |||
4584 | std::tie(ToLocation, ToAtStartLoc, ToCategoryNameLoc) = *Imp; | |||
4585 | else | |||
4586 | return Imp.takeError(); | |||
4587 | ||||
4588 | if (GetImportedOrCreateDecl( | |||
4589 | ToImpl, D, Importer.getToContext(), DC, | |||
4590 | Importer.Import(D->getIdentifier()), Category->getClassInterface(), | |||
4591 | ToLocation, ToAtStartLoc, ToCategoryNameLoc)) | |||
4592 | return ToImpl; | |||
4593 | ||||
4594 | ToImpl->setLexicalDeclContext(LexicalDC); | |||
4595 | LexicalDC->addDeclInternal(ToImpl); | |||
4596 | Category->setImplementation(ToImpl); | |||
4597 | } | |||
4598 | ||||
4599 | Importer.MapImported(D, ToImpl); | |||
4600 | if (Error Err = ImportDeclContext(D)) | |||
4601 | return std::move(Err); | |||
4602 | ||||
4603 | return ToImpl; | |||
4604 | } | |||
4605 | ||||
4606 | ExpectedDecl | |||
4607 | ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { | |||
4608 | // Find the corresponding interface. | |||
4609 | ObjCInterfaceDecl *Iface; | |||
4610 | if (Error Err = importInto(Iface, D->getClassInterface())) | |||
4611 | return std::move(Err); | |||
4612 | ||||
4613 | // Import the superclass, if any. | |||
4614 | ObjCInterfaceDecl *Super; | |||
4615 | if (Error Err = importInto(Super, D->getSuperClass())) | |||
4616 | return std::move(Err); | |||
4617 | ||||
4618 | ObjCImplementationDecl *Impl = Iface->getImplementation(); | |||
4619 | if (!Impl) { | |||
4620 | // We haven't imported an implementation yet. Create a new @implementation | |||
4621 | // now. | |||
4622 | DeclContext *DC, *LexicalDC; | |||
4623 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
4624 | return std::move(Err); | |||
4625 | ||||
4626 | SourceLocation ToLocation, ToAtStartLoc, ToSuperClassLoc; | |||
4627 | SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc; | |||
4628 | if (auto Imp = importSeq( | |||
4629 | D->getLocation(), D->getAtStartLoc(), D->getSuperClassLoc(), | |||
4630 | D->getIvarLBraceLoc(), D->getIvarRBraceLoc())) | |||
4631 | std::tie( | |||
4632 | ToLocation, ToAtStartLoc, ToSuperClassLoc, | |||
4633 | ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp; | |||
4634 | else | |||
4635 | return Imp.takeError(); | |||
4636 | ||||
4637 | if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(), | |||
4638 | DC, Iface, Super, | |||
4639 | ToLocation, | |||
4640 | ToAtStartLoc, | |||
4641 | ToSuperClassLoc, | |||
4642 | ToIvarLBraceLoc, | |||
4643 | ToIvarRBraceLoc)) | |||
4644 | return Impl; | |||
4645 | ||||
4646 | Impl->setLexicalDeclContext(LexicalDC); | |||
4647 | ||||
4648 | // Associate the implementation with the class it implements. | |||
4649 | Iface->setImplementation(Impl); | |||
4650 | Importer.MapImported(D, Iface->getImplementation()); | |||
4651 | } else { | |||
4652 | Importer.MapImported(D, Iface->getImplementation()); | |||
4653 | ||||
4654 | // Verify that the existing @implementation has the same superclass. | |||
4655 | if ((Super && !Impl->getSuperClass()) || | |||
4656 | (!Super && Impl->getSuperClass()) || | |||
4657 | (Super && Impl->getSuperClass() && | |||
4658 | !declaresSameEntity(Super->getCanonicalDecl(), | |||
4659 | Impl->getSuperClass()))) { | |||
4660 | Importer.ToDiag(Impl->getLocation(), | |||
4661 | diag::warn_odr_objc_superclass_inconsistent) | |||
4662 | << Iface->getDeclName(); | |||
4663 | // FIXME: It would be nice to have the location of the superclass | |||
4664 | // below. | |||
4665 | if (Impl->getSuperClass()) | |||
4666 | Importer.ToDiag(Impl->getLocation(), | |||
4667 | diag::note_odr_objc_superclass) | |||
4668 | << Impl->getSuperClass()->getDeclName(); | |||
4669 | else | |||
4670 | Importer.ToDiag(Impl->getLocation(), | |||
4671 | diag::note_odr_objc_missing_superclass); | |||
4672 | if (D->getSuperClass()) | |||
4673 | Importer.FromDiag(D->getLocation(), | |||
4674 | diag::note_odr_objc_superclass) | |||
4675 | << D->getSuperClass()->getDeclName(); | |||
4676 | else | |||
4677 | Importer.FromDiag(D->getLocation(), | |||
4678 | diag::note_odr_objc_missing_superclass); | |||
4679 | ||||
4680 | return make_error<ImportError>(ImportError::NameConflict); | |||
4681 | } | |||
4682 | } | |||
4683 | ||||
4684 | // Import all of the members of this @implementation. | |||
4685 | if (Error Err = ImportDeclContext(D)) | |||
4686 | return std::move(Err); | |||
4687 | ||||
4688 | return Impl; | |||
4689 | } | |||
4690 | ||||
4691 | ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { | |||
4692 | // Import the major distinguishing characteristics of an @property. | |||
4693 | DeclContext *DC, *LexicalDC; | |||
4694 | DeclarationName Name; | |||
4695 | SourceLocation Loc; | |||
4696 | NamedDecl *ToD; | |||
4697 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4698 | return std::move(Err); | |||
4699 | if (ToD) | |||
4700 | return ToD; | |||
4701 | ||||
4702 | // Check whether we have already imported this property. | |||
4703 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
4704 | for (auto *FoundDecl : FoundDecls) { | |||
4705 | if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) { | |||
4706 | // Check property types. | |||
4707 | if (!Importer.IsStructurallyEquivalent(D->getType(), | |||
4708 | FoundProp->getType())) { | |||
4709 | Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent) | |||
4710 | << Name << D->getType() << FoundProp->getType(); | |||
4711 | Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here) | |||
4712 | << FoundProp->getType(); | |||
4713 | ||||
4714 | return make_error<ImportError>(ImportError::NameConflict); | |||
4715 | } | |||
4716 | ||||
4717 | // FIXME: Check property attributes, getters, setters, etc.? | |||
4718 | ||||
4719 | // Consider these properties to be equivalent. | |||
4720 | Importer.MapImported(D, FoundProp); | |||
4721 | return FoundProp; | |||
4722 | } | |||
4723 | } | |||
4724 | ||||
4725 | QualType ToType; | |||
4726 | TypeSourceInfo *ToTypeSourceInfo; | |||
4727 | SourceLocation ToAtLoc, ToLParenLoc; | |||
4728 | if (auto Imp = importSeq( | |||
4729 | D->getType(), D->getTypeSourceInfo(), D->getAtLoc(), D->getLParenLoc())) | |||
4730 | std::tie(ToType, ToTypeSourceInfo, ToAtLoc, ToLParenLoc) = *Imp; | |||
4731 | else | |||
4732 | return Imp.takeError(); | |||
4733 | ||||
4734 | // Create the new property. | |||
4735 | ObjCPropertyDecl *ToProperty; | |||
4736 | if (GetImportedOrCreateDecl( | |||
4737 | ToProperty, D, Importer.getToContext(), DC, Loc, | |||
4738 | Name.getAsIdentifierInfo(), ToAtLoc, | |||
4739 | ToLParenLoc, ToType, | |||
4740 | ToTypeSourceInfo, D->getPropertyImplementation())) | |||
4741 | return ToProperty; | |||
4742 | ||||
4743 | Selector ToGetterName, ToSetterName; | |||
4744 | SourceLocation ToGetterNameLoc, ToSetterNameLoc; | |||
4745 | ObjCMethodDecl *ToGetterMethodDecl, *ToSetterMethodDecl; | |||
4746 | ObjCIvarDecl *ToPropertyIvarDecl; | |||
4747 | if (auto Imp = importSeq( | |||
4748 | D->getGetterName(), D->getSetterName(), | |||
4749 | D->getGetterNameLoc(), D->getSetterNameLoc(), | |||
4750 | D->getGetterMethodDecl(), D->getSetterMethodDecl(), | |||
4751 | D->getPropertyIvarDecl())) | |||
4752 | std::tie( | |||
4753 | ToGetterName, ToSetterName, | |||
4754 | ToGetterNameLoc, ToSetterNameLoc, | |||
4755 | ToGetterMethodDecl, ToSetterMethodDecl, | |||
4756 | ToPropertyIvarDecl) = *Imp; | |||
4757 | else | |||
4758 | return Imp.takeError(); | |||
4759 | ||||
4760 | ToProperty->setLexicalDeclContext(LexicalDC); | |||
4761 | LexicalDC->addDeclInternal(ToProperty); | |||
4762 | ||||
4763 | ToProperty->setPropertyAttributes(D->getPropertyAttributes()); | |||
4764 | ToProperty->setPropertyAttributesAsWritten( | |||
4765 | D->getPropertyAttributesAsWritten()); | |||
4766 | ToProperty->setGetterName(ToGetterName, ToGetterNameLoc); | |||
4767 | ToProperty->setSetterName(ToSetterName, ToSetterNameLoc); | |||
4768 | ToProperty->setGetterMethodDecl(ToGetterMethodDecl); | |||
4769 | ToProperty->setSetterMethodDecl(ToSetterMethodDecl); | |||
4770 | ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl); | |||
4771 | return ToProperty; | |||
4772 | } | |||
4773 | ||||
4774 | ExpectedDecl | |||
4775 | ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { | |||
4776 | ObjCPropertyDecl *Property; | |||
4777 | if (Error Err = importInto(Property, D->getPropertyDecl())) | |||
4778 | return std::move(Err); | |||
4779 | ||||
4780 | DeclContext *DC, *LexicalDC; | |||
4781 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
4782 | return std::move(Err); | |||
4783 | ||||
4784 | auto *InImpl = cast<ObjCImplDecl>(LexicalDC); | |||
4785 | ||||
4786 | // Import the ivar (for an @synthesize). | |||
4787 | ObjCIvarDecl *Ivar = nullptr; | |||
4788 | if (Error Err = importInto(Ivar, D->getPropertyIvarDecl())) | |||
4789 | return std::move(Err); | |||
4790 | ||||
4791 | ObjCPropertyImplDecl *ToImpl | |||
4792 | = InImpl->FindPropertyImplDecl(Property->getIdentifier(), | |||
4793 | Property->getQueryKind()); | |||
4794 | if (!ToImpl) { | |||
4795 | SourceLocation ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc; | |||
4796 | if (auto Imp = importSeq( | |||
4797 | D->getBeginLoc(), D->getLocation(), D->getPropertyIvarDeclLoc())) | |||
4798 | std::tie(ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc) = *Imp; | |||
4799 | else | |||
4800 | return Imp.takeError(); | |||
4801 | ||||
4802 | if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC, | |||
4803 | ToBeginLoc, | |||
4804 | ToLocation, Property, | |||
4805 | D->getPropertyImplementation(), Ivar, | |||
4806 | ToPropertyIvarDeclLoc)) | |||
4807 | return ToImpl; | |||
4808 | ||||
4809 | ToImpl->setLexicalDeclContext(LexicalDC); | |||
4810 | LexicalDC->addDeclInternal(ToImpl); | |||
4811 | } else { | |||
4812 | // Check that we have the same kind of property implementation (@synthesize | |||
4813 | // vs. @dynamic). | |||
4814 | if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { | |||
4815 | Importer.ToDiag(ToImpl->getLocation(), | |||
4816 | diag::warn_odr_objc_property_impl_kind_inconsistent) | |||
4817 | << Property->getDeclName() | |||
4818 | << (ToImpl->getPropertyImplementation() | |||
4819 | == ObjCPropertyImplDecl::Dynamic); | |||
4820 | Importer.FromDiag(D->getLocation(), | |||
4821 | diag::note_odr_objc_property_impl_kind) | |||
4822 | << D->getPropertyDecl()->getDeclName() | |||
4823 | << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); | |||
4824 | ||||
4825 | return make_error<ImportError>(ImportError::NameConflict); | |||
4826 | } | |||
4827 | ||||
4828 | // For @synthesize, check that we have the same | |||
4829 | if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize && | |||
4830 | Ivar != ToImpl->getPropertyIvarDecl()) { | |||
4831 | Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), | |||
4832 | diag::warn_odr_objc_synthesize_ivar_inconsistent) | |||
4833 | << Property->getDeclName() | |||
4834 | << ToImpl->getPropertyIvarDecl()->getDeclName() | |||
4835 | << Ivar->getDeclName(); | |||
4836 | Importer.FromDiag(D->getPropertyIvarDeclLoc(), | |||
4837 | diag::note_odr_objc_synthesize_ivar_here) | |||
4838 | << D->getPropertyIvarDecl()->getDeclName(); | |||
4839 | ||||
4840 | return make_error<ImportError>(ImportError::NameConflict); | |||
4841 | } | |||
4842 | ||||
4843 | // Merge the existing implementation with the new implementation. | |||
4844 | Importer.MapImported(D, ToImpl); | |||
4845 | } | |||
4846 | ||||
4847 | return ToImpl; | |||
4848 | } | |||
4849 | ||||
4850 | ExpectedDecl | |||
4851 | ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { | |||
4852 | // For template arguments, we adopt the translation unit as our declaration | |||
4853 | // context. This context will be fixed when the actual template declaration | |||
4854 | // is created. | |||
4855 | ||||
4856 | // FIXME: Import default argument. | |||
4857 | ||||
4858 | ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); | |||
4859 | if (!BeginLocOrErr) | |||
4860 | return BeginLocOrErr.takeError(); | |||
4861 | ||||
4862 | ExpectedSLoc LocationOrErr = import(D->getLocation()); | |||
4863 | if (!LocationOrErr) | |||
4864 | return LocationOrErr.takeError(); | |||
4865 | ||||
4866 | TemplateTypeParmDecl *ToD = nullptr; | |||
4867 | (void)GetImportedOrCreateDecl( | |||
4868 | ToD, D, Importer.getToContext(), | |||
4869 | Importer.getToContext().getTranslationUnitDecl(), | |||
4870 | *BeginLocOrErr, *LocationOrErr, | |||
4871 | D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()), | |||
4872 | D->wasDeclaredWithTypename(), D->isParameterPack()); | |||
4873 | return ToD; | |||
4874 | } | |||
4875 | ||||
4876 | ExpectedDecl | |||
4877 | ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { | |||
4878 | DeclarationName ToDeclName; | |||
4879 | SourceLocation ToLocation, ToInnerLocStart; | |||
4880 | QualType ToType; | |||
4881 | TypeSourceInfo *ToTypeSourceInfo; | |||
4882 | if (auto Imp = importSeq( | |||
4883 | D->getDeclName(), D->getLocation(), D->getType(), D->getTypeSourceInfo(), | |||
4884 | D->getInnerLocStart())) | |||
4885 | std::tie( | |||
4886 | ToDeclName, ToLocation, ToType, ToTypeSourceInfo, | |||
4887 | ToInnerLocStart) = *Imp; | |||
4888 | else | |||
4889 | return Imp.takeError(); | |||
4890 | ||||
4891 | // FIXME: Import default argument. | |||
4892 | ||||
4893 | NonTypeTemplateParmDecl *ToD = nullptr; | |||
4894 | (void)GetImportedOrCreateDecl( | |||
4895 | ToD, D, Importer.getToContext(), | |||
4896 | Importer.getToContext().getTranslationUnitDecl(), | |||
4897 | ToInnerLocStart, ToLocation, D->getDepth(), | |||
4898 | D->getPosition(), ToDeclName.getAsIdentifierInfo(), ToType, | |||
4899 | D->isParameterPack(), ToTypeSourceInfo); | |||
4900 | return ToD; | |||
4901 | } | |||
4902 | ||||
4903 | ExpectedDecl | |||
4904 | ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { | |||
4905 | // Import the name of this declaration. | |||
4906 | auto NameOrErr = import(D->getDeclName()); | |||
4907 | if (!NameOrErr) | |||
4908 | return NameOrErr.takeError(); | |||
4909 | ||||
4910 | // Import the location of this declaration. | |||
4911 | ExpectedSLoc LocationOrErr = import(D->getLocation()); | |||
4912 | if (!LocationOrErr) | |||
4913 | return LocationOrErr.takeError(); | |||
4914 | ||||
4915 | // Import template parameters. | |||
4916 | auto TemplateParamsOrErr = import(D->getTemplateParameters()); | |||
4917 | if (!TemplateParamsOrErr) | |||
4918 | return TemplateParamsOrErr.takeError(); | |||
4919 | ||||
4920 | // FIXME: Import default argument. | |||
4921 | ||||
4922 | TemplateTemplateParmDecl *ToD = nullptr; | |||
4923 | (void)GetImportedOrCreateDecl( | |||
4924 | ToD, D, Importer.getToContext(), | |||
4925 | Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr, | |||
4926 | D->getDepth(), D->getPosition(), D->isParameterPack(), | |||
4927 | (*NameOrErr).getAsIdentifierInfo(), | |||
4928 | *TemplateParamsOrErr); | |||
4929 | return ToD; | |||
4930 | } | |||
4931 | ||||
4932 | // Returns the definition for a (forward) declaration of a TemplateDecl, if | |||
4933 | // it has any definition in the redecl chain. | |||
4934 | template <typename T> static auto getTemplateDefinition(T *D) -> T * { | |||
4935 | assert(D->getTemplatedDecl() && "Should be called on templates only")((D->getTemplatedDecl() && "Should be called on templates only" ) ? static_cast<void> (0) : __assert_fail ("D->getTemplatedDecl() && \"Should be called on templates only\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 4935, __PRETTY_FUNCTION__)); | |||
4936 | auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition(); | |||
4937 | if (!ToTemplatedDef) | |||
4938 | return nullptr; | |||
4939 | auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate(); | |||
4940 | return cast_or_null<T>(TemplateWithDef); | |||
4941 | } | |||
4942 | ||||
4943 | ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { | |||
4944 | bool IsFriend = D->getFriendObjectKind() != Decl::FOK_None; | |||
4945 | ||||
4946 | // Import the major distinguishing characteristics of this class template. | |||
4947 | DeclContext *DC, *LexicalDC; | |||
4948 | DeclarationName Name; | |||
4949 | SourceLocation Loc; | |||
4950 | NamedDecl *ToD; | |||
4951 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
4952 | return std::move(Err); | |||
4953 | if (ToD) | |||
4954 | return ToD; | |||
4955 | ||||
4956 | ClassTemplateDecl *FoundByLookup = nullptr; | |||
4957 | ||||
4958 | // We may already have a template of the same name; try to find and match it. | |||
4959 | if (!DC->isFunctionOrMethod()) { | |||
4960 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
4961 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
4962 | for (auto *FoundDecl : FoundDecls) { | |||
4963 | if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary | | |||
4964 | Decl::IDNS_TagFriend)) | |||
4965 | continue; | |||
4966 | ||||
4967 | Decl *Found = FoundDecl; | |||
4968 | auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found); | |||
4969 | if (FoundTemplate) { | |||
4970 | ||||
4971 | if (IsStructuralMatch(D, FoundTemplate)) { | |||
4972 | ClassTemplateDecl *TemplateWithDef = | |||
4973 | getTemplateDefinition(FoundTemplate); | |||
4974 | if (D->isThisDeclarationADefinition() && TemplateWithDef) { | |||
4975 | return Importer.MapImported(D, TemplateWithDef); | |||
4976 | } | |||
4977 | FoundByLookup = FoundTemplate; | |||
4978 | break; | |||
4979 | } | |||
4980 | } | |||
4981 | ||||
4982 | ConflictingDecls.push_back(FoundDecl); | |||
4983 | } | |||
4984 | ||||
4985 | if (!ConflictingDecls.empty()) { | |||
4986 | Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary, | |||
4987 | ConflictingDecls.data(), | |||
4988 | ConflictingDecls.size()); | |||
4989 | } | |||
4990 | ||||
4991 | if (!Name) | |||
4992 | return make_error<ImportError>(ImportError::NameConflict); | |||
4993 | } | |||
4994 | ||||
4995 | CXXRecordDecl *FromTemplated = D->getTemplatedDecl(); | |||
4996 | ||||
4997 | // Create the declaration that is being templated. | |||
4998 | CXXRecordDecl *ToTemplated; | |||
4999 | if (Error Err = importInto(ToTemplated, FromTemplated)) | |||
5000 | return std::move(Err); | |||
5001 | ||||
5002 | // Create the class template declaration itself. | |||
5003 | auto TemplateParamsOrErr = import(D->getTemplateParameters()); | |||
5004 | if (!TemplateParamsOrErr) | |||
5005 | return TemplateParamsOrErr.takeError(); | |||
5006 | ||||
5007 | ClassTemplateDecl *D2; | |||
5008 | if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name, | |||
5009 | *TemplateParamsOrErr, ToTemplated)) | |||
5010 | return D2; | |||
5011 | ||||
5012 | ToTemplated->setDescribedClassTemplate(D2); | |||
5013 | ||||
5014 | D2->setAccess(D->getAccess()); | |||
5015 | D2->setLexicalDeclContext(LexicalDC); | |||
5016 | ||||
5017 | if (D->getDeclContext()->containsDeclAndLoad(D)) | |||
5018 | DC->addDeclInternal(D2); | |||
5019 | if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D)) | |||
5020 | LexicalDC->addDeclInternal(D2); | |||
5021 | ||||
5022 | if (FoundByLookup) { | |||
5023 | auto *Recent = | |||
5024 | const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl()); | |||
5025 | ||||
5026 | // It is possible that during the import of the class template definition | |||
5027 | // we start the import of a fwd friend decl of the very same class template | |||
5028 | // and we add the fwd friend decl to the lookup table. But the ToTemplated | |||
5029 | // had been created earlier and by that time the lookup could not find | |||
5030 | // anything existing, so it has no previous decl. Later, (still during the | |||
5031 | // import of the fwd friend decl) we start to import the definition again | |||
5032 | // and this time the lookup finds the previous fwd friend class template. | |||
5033 | // In this case we must set up the previous decl for the templated decl. | |||
5034 | if (!ToTemplated->getPreviousDecl()) { | |||
5035 | assert(FoundByLookup->getTemplatedDecl() &&((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set" ) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 5036, __PRETTY_FUNCTION__)) | |||
5036 | "Found decl must have its templated decl set")((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set" ) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 5036, __PRETTY_FUNCTION__)); | |||
5037 | CXXRecordDecl *PrevTemplated = | |||
5038 | FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); | |||
5039 | if (ToTemplated != PrevTemplated) | |||
5040 | ToTemplated->setPreviousDecl(PrevTemplated); | |||
5041 | } | |||
5042 | ||||
5043 | D2->setPreviousDecl(Recent); | |||
5044 | } | |||
5045 | ||||
5046 | if (LexicalDC != DC && IsFriend) | |||
5047 | DC->makeDeclVisibleInContext(D2); | |||
5048 | ||||
5049 | if (FromTemplated->isCompleteDefinition() && | |||
5050 | !ToTemplated->isCompleteDefinition()) { | |||
5051 | // FIXME: Import definition! | |||
5052 | } | |||
5053 | ||||
5054 | return D2; | |||
5055 | } | |||
5056 | ||||
5057 | ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl( | |||
5058 | ClassTemplateSpecializationDecl *D) { | |||
5059 | ClassTemplateDecl *ClassTemplate; | |||
5060 | if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate())) | |||
5061 | return std::move(Err); | |||
5062 | ||||
5063 | // Import the context of this declaration. | |||
5064 | DeclContext *DC, *LexicalDC; | |||
5065 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
5066 | return std::move(Err); | |||
5067 | ||||
5068 | // Import template arguments. | |||
5069 | SmallVector<TemplateArgument, 2> TemplateArgs; | |||
5070 | if (Error Err = ImportTemplateArguments( | |||
5071 | D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) | |||
5072 | return std::move(Err); | |||
5073 | ||||
5074 | // Try to find an existing specialization with these template arguments. | |||
5075 | void *InsertPos = nullptr; | |||
5076 | ClassTemplateSpecializationDecl *PrevDecl = nullptr; | |||
5077 | ClassTemplatePartialSpecializationDecl *PartialSpec = | |||
5078 | dyn_cast<ClassTemplatePartialSpecializationDecl>(D); | |||
5079 | if (PartialSpec) | |||
5080 | PrevDecl = | |||
5081 | ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos); | |||
5082 | else | |||
5083 | PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos); | |||
5084 | ||||
5085 | if (PrevDecl) { | |||
5086 | if (IsStructuralMatch(D, PrevDecl)) { | |||
5087 | if (D->isThisDeclarationADefinition() && PrevDecl->getDefinition()) { | |||
5088 | Importer.MapImported(D, PrevDecl->getDefinition()); | |||
5089 | // Import those default field initializers which have been | |||
5090 | // instantiated in the "From" context, but not in the "To" context. | |||
5091 | for (auto *FromField : D->fields()) { | |||
5092 | auto ToOrErr = import(FromField); | |||
5093 | if (!ToOrErr) | |||
5094 | return ToOrErr.takeError(); | |||
5095 | } | |||
5096 | ||||
5097 | // Import those methods which have been instantiated in the | |||
5098 | // "From" context, but not in the "To" context. | |||
5099 | for (CXXMethodDecl *FromM : D->methods()) { | |||
5100 | auto ToOrErr = import(FromM); | |||
5101 | if (!ToOrErr) | |||
5102 | return ToOrErr.takeError(); | |||
5103 | } | |||
5104 | ||||
5105 | // TODO Import instantiated default arguments. | |||
5106 | // TODO Import instantiated exception specifications. | |||
5107 | // | |||
5108 | // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint | |||
5109 | // what else could be fused during an AST merge. | |||
5110 | return PrevDecl; | |||
5111 | } | |||
5112 | } else { // ODR violation. | |||
5113 | // FIXME HandleNameConflict | |||
5114 | return nullptr; | |||
5115 | } | |||
5116 | } | |||
5117 | ||||
5118 | // Import the location of this declaration. | |||
5119 | ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); | |||
5120 | if (!BeginLocOrErr) | |||
5121 | return BeginLocOrErr.takeError(); | |||
5122 | ExpectedSLoc IdLocOrErr = import(D->getLocation()); | |||
5123 | if (!IdLocOrErr) | |||
5124 | return IdLocOrErr.takeError(); | |||
5125 | ||||
5126 | // Create the specialization. | |||
5127 | ClassTemplateSpecializationDecl *D2 = nullptr; | |||
5128 | if (PartialSpec) { | |||
5129 | // Import TemplateArgumentListInfo. | |||
5130 | TemplateArgumentListInfo ToTAInfo; | |||
5131 | const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten(); | |||
5132 | if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo)) | |||
5133 | return std::move(Err); | |||
5134 | ||||
5135 | QualType CanonInjType; | |||
5136 | if (Error Err = importInto( | |||
5137 | CanonInjType, PartialSpec->getInjectedSpecializationType())) | |||
5138 | return std::move(Err); | |||
5139 | CanonInjType = CanonInjType.getCanonicalType(); | |||
5140 | ||||
5141 | auto ToTPListOrErr = import(PartialSpec->getTemplateParameters()); | |||
5142 | if (!ToTPListOrErr) | |||
5143 | return ToTPListOrErr.takeError(); | |||
5144 | ||||
5145 | if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>( | |||
5146 | D2, D, Importer.getToContext(), D->getTagKind(), DC, | |||
5147 | *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, ClassTemplate, | |||
5148 | llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()), | |||
5149 | ToTAInfo, CanonInjType, | |||
5150 | cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl))) | |||
5151 | return D2; | |||
5152 | ||||
5153 | // Update InsertPos, because preceding import calls may have invalidated | |||
5154 | // it by adding new specializations. | |||
5155 | if (!ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos)) | |||
5156 | // Add this partial specialization to the class template. | |||
5157 | ClassTemplate->AddPartialSpecialization( | |||
5158 | cast<ClassTemplatePartialSpecializationDecl>(D2), InsertPos); | |||
5159 | ||||
5160 | } else { // Not a partial specialization. | |||
5161 | if (GetImportedOrCreateDecl( | |||
5162 | D2, D, Importer.getToContext(), D->getTagKind(), DC, | |||
5163 | *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs, | |||
5164 | PrevDecl)) | |||
5165 | return D2; | |||
5166 | ||||
5167 | // Update InsertPos, because preceding import calls may have invalidated | |||
5168 | // it by adding new specializations. | |||
5169 | if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos)) | |||
5170 | // Add this specialization to the class template. | |||
5171 | ClassTemplate->AddSpecialization(D2, InsertPos); | |||
5172 | } | |||
5173 | ||||
5174 | D2->setSpecializationKind(D->getSpecializationKind()); | |||
5175 | ||||
5176 | // Set the context of this specialization/instantiation. | |||
5177 | D2->setLexicalDeclContext(LexicalDC); | |||
5178 | ||||
5179 | // Add to the DC only if it was an explicit specialization/instantiation. | |||
5180 | if (D2->isExplicitInstantiationOrSpecialization()) { | |||
5181 | LexicalDC->addDeclInternal(D2); | |||
5182 | } | |||
5183 | ||||
5184 | // Import the qualifier, if any. | |||
5185 | if (auto LocOrErr = import(D->getQualifierLoc())) | |||
5186 | D2->setQualifierInfo(*LocOrErr); | |||
5187 | else | |||
5188 | return LocOrErr.takeError(); | |||
5189 | ||||
5190 | if (auto *TSI = D->getTypeAsWritten()) { | |||
5191 | if (auto TInfoOrErr = import(TSI)) | |||
5192 | D2->setTypeAsWritten(*TInfoOrErr); | |||
5193 | else | |||
5194 | return TInfoOrErr.takeError(); | |||
5195 | ||||
5196 | if (auto LocOrErr = import(D->getTemplateKeywordLoc())) | |||
5197 | D2->setTemplateKeywordLoc(*LocOrErr); | |||
5198 | else | |||
5199 | return LocOrErr.takeError(); | |||
5200 | ||||
5201 | if (auto LocOrErr = import(D->getExternLoc())) | |||
5202 | D2->setExternLoc(*LocOrErr); | |||
5203 | else | |||
5204 | return LocOrErr.takeError(); | |||
5205 | } | |||
5206 | ||||
5207 | if (D->getPointOfInstantiation().isValid()) { | |||
5208 | if (auto POIOrErr = import(D->getPointOfInstantiation())) | |||
5209 | D2->setPointOfInstantiation(*POIOrErr); | |||
5210 | else | |||
5211 | return POIOrErr.takeError(); | |||
5212 | } | |||
5213 | ||||
5214 | D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind()); | |||
5215 | ||||
5216 | if (D->isCompleteDefinition()) | |||
5217 | if (Error Err = ImportDefinition(D, D2)) | |||
5218 | return std::move(Err); | |||
5219 | ||||
5220 | return D2; | |||
5221 | } | |||
5222 | ||||
5223 | ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) { | |||
5224 | // If this variable has a definition in the translation unit we're coming | |||
5225 | // from, | |||
5226 | // but this particular declaration is not that definition, import the | |||
5227 | // definition and map to that. | |||
5228 | auto *Definition = | |||
5229 | cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition()); | |||
5230 | if (Definition && Definition != D->getTemplatedDecl()) { | |||
5231 | if (ExpectedDecl ImportedDefOrErr = import( | |||
5232 | Definition->getDescribedVarTemplate())) | |||
5233 | return Importer.MapImported(D, *ImportedDefOrErr); | |||
5234 | else | |||
5235 | return ImportedDefOrErr.takeError(); | |||
5236 | } | |||
5237 | ||||
5238 | // Import the major distinguishing characteristics of this variable template. | |||
5239 | DeclContext *DC, *LexicalDC; | |||
5240 | DeclarationName Name; | |||
5241 | SourceLocation Loc; | |||
5242 | NamedDecl *ToD; | |||
5243 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
5244 | return std::move(Err); | |||
5245 | if (ToD) | |||
5246 | return ToD; | |||
5247 | ||||
5248 | // We may already have a template of the same name; try to find and match it. | |||
5249 | assert(!DC->isFunctionOrMethod() &&((!DC->isFunctionOrMethod() && "Variable templates cannot be declared at function scope" ) ? static_cast<void> (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 5250, __PRETTY_FUNCTION__)) | |||
5250 | "Variable templates cannot be declared at function scope")((!DC->isFunctionOrMethod() && "Variable templates cannot be declared at function scope" ) ? static_cast<void> (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 5250, __PRETTY_FUNCTION__)); | |||
5251 | SmallVector<NamedDecl *, 4> ConflictingDecls; | |||
5252 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
5253 | for (auto *FoundDecl : FoundDecls) { | |||
5254 | if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | |||
5255 | continue; | |||
5256 | ||||
5257 | Decl *Found = FoundDecl; | |||
5258 | if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) { | |||
5259 | if (IsStructuralMatch(D, FoundTemplate)) { | |||
5260 | // The variable templates structurally match; call it the same template. | |||
5261 | Importer.MapImported(D->getTemplatedDecl(), | |||
5262 | FoundTemplate->getTemplatedDecl()); | |||
5263 | return Importer.MapImported(D, FoundTemplate); | |||
5264 | } | |||
5265 | } | |||
5266 | ||||
5267 | ConflictingDecls.push_back(FoundDecl); | |||
5268 | } | |||
5269 | ||||
5270 | if (!ConflictingDecls.empty()) { | |||
5271 | Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary, | |||
5272 | ConflictingDecls.data(), | |||
5273 | ConflictingDecls.size()); | |||
5274 | } | |||
5275 | ||||
5276 | if (!Name) | |||
5277 | // FIXME: Is it possible to get other error than name conflict? | |||
5278 | // (Put this `if` into the previous `if`?) | |||
5279 | return make_error<ImportError>(ImportError::NameConflict); | |||
5280 | ||||
5281 | VarDecl *DTemplated = D->getTemplatedDecl(); | |||
5282 | ||||
5283 | // Import the type. | |||
5284 | // FIXME: Value not used? | |||
5285 | ExpectedType TypeOrErr = import(DTemplated->getType()); | |||
5286 | if (!TypeOrErr) | |||
5287 | return TypeOrErr.takeError(); | |||
5288 | ||||
5289 | // Create the declaration that is being templated. | |||
5290 | VarDecl *ToTemplated; | |||
5291 | if (Error Err = importInto(ToTemplated, DTemplated)) | |||
5292 | return std::move(Err); | |||
5293 | ||||
5294 | // Create the variable template declaration itself. | |||
5295 | auto TemplateParamsOrErr = import(D->getTemplateParameters()); | |||
5296 | if (!TemplateParamsOrErr) | |||
5297 | return TemplateParamsOrErr.takeError(); | |||
5298 | ||||
5299 | VarTemplateDecl *ToVarTD; | |||
5300 | if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc, | |||
5301 | Name, *TemplateParamsOrErr, ToTemplated)) | |||
5302 | return ToVarTD; | |||
5303 | ||||
5304 | ToTemplated->setDescribedVarTemplate(ToVarTD); | |||
5305 | ||||
5306 | ToVarTD->setAccess(D->getAccess()); | |||
5307 | ToVarTD->setLexicalDeclContext(LexicalDC); | |||
5308 | LexicalDC->addDeclInternal(ToVarTD); | |||
5309 | ||||
5310 | if (DTemplated->isThisDeclarationADefinition() && | |||
5311 | !ToTemplated->isThisDeclarationADefinition()) { | |||
5312 | // FIXME: Import definition! | |||
5313 | } | |||
5314 | ||||
5315 | return ToVarTD; | |||
5316 | } | |||
5317 | ||||
5318 | ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl( | |||
5319 | VarTemplateSpecializationDecl *D) { | |||
5320 | // If this record has a definition in the translation unit we're coming from, | |||
5321 | // but this particular declaration is not that definition, import the | |||
5322 | // definition and map to that. | |||
5323 | VarDecl *Definition = D->getDefinition(); | |||
5324 | if (Definition && Definition != D) { | |||
5325 | if (ExpectedDecl ImportedDefOrErr = import(Definition)) | |||
5326 | return Importer.MapImported(D, *ImportedDefOrErr); | |||
5327 | else | |||
5328 | return ImportedDefOrErr.takeError(); | |||
5329 | } | |||
5330 | ||||
5331 | VarTemplateDecl *VarTemplate = nullptr; | |||
5332 | if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate())) | |||
5333 | return std::move(Err); | |||
5334 | ||||
5335 | // Import the context of this declaration. | |||
5336 | DeclContext *DC, *LexicalDC; | |||
5337 | if (Error Err = ImportDeclContext(D, DC, LexicalDC)) | |||
5338 | return std::move(Err); | |||
5339 | ||||
5340 | // Import the location of this declaration. | |||
5341 | ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); | |||
5342 | if (!BeginLocOrErr) | |||
5343 | return BeginLocOrErr.takeError(); | |||
5344 | ||||
5345 | auto IdLocOrErr = import(D->getLocation()); | |||
5346 | if (!IdLocOrErr) | |||
5347 | return IdLocOrErr.takeError(); | |||
5348 | ||||
5349 | // Import template arguments. | |||
5350 | SmallVector<TemplateArgument, 2> TemplateArgs; | |||
5351 | if (Error Err = ImportTemplateArguments( | |||
5352 | D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) | |||
5353 | return std::move(Err); | |||
5354 | ||||
5355 | // Try to find an existing specialization with these template arguments. | |||
5356 | void *InsertPos = nullptr; | |||
5357 | VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization( | |||
5358 | TemplateArgs, InsertPos); | |||
5359 | if (D2) { | |||
5360 | // We already have a variable template specialization with these template | |||
5361 | // arguments. | |||
5362 | ||||
5363 | // FIXME: Check for specialization vs. instantiation errors. | |||
5364 | ||||
5365 | if (VarDecl *FoundDef = D2->getDefinition()) { | |||
5366 | if (!D->isThisDeclarationADefinition() || | |||
5367 | IsStructuralMatch(D, FoundDef)) { | |||
5368 | // The record types structurally match, or the "from" translation | |||
5369 | // unit only had a forward declaration anyway; call it the same | |||
5370 | // variable. | |||
5371 | return Importer.MapImported(D, FoundDef); | |||
5372 | } | |||
5373 | } | |||
5374 | } else { | |||
5375 | // Import the type. | |||
5376 | QualType T; | |||
5377 | if (Error Err = importInto(T, D->getType())) | |||
5378 | return std::move(Err); | |||
5379 | ||||
5380 | auto TInfoOrErr = import(D->getTypeSourceInfo()); | |||
5381 | if (!TInfoOrErr) | |||
5382 | return TInfoOrErr.takeError(); | |||
5383 | ||||
5384 | TemplateArgumentListInfo ToTAInfo; | |||
5385 | if (Error Err = ImportTemplateArgumentListInfo( | |||
5386 | D->getTemplateArgsInfo(), ToTAInfo)) | |||
5387 | return std::move(Err); | |||
5388 | ||||
5389 | using PartVarSpecDecl = VarTemplatePartialSpecializationDecl; | |||
5390 | // Create a new specialization. | |||
5391 | if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) { | |||
5392 | // Import TemplateArgumentListInfo | |||
5393 | TemplateArgumentListInfo ArgInfos; | |||
5394 | const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten(); | |||
5395 | // NOTE: FromTAArgsAsWritten and template parameter list are non-null. | |||
5396 | if (Error Err = ImportTemplateArgumentListInfo( | |||
5397 | *FromTAArgsAsWritten, ArgInfos)) | |||
5398 | return std::move(Err); | |||
5399 | ||||
5400 | auto ToTPListOrErr = import(FromPartial->getTemplateParameters()); | |||
5401 | if (!ToTPListOrErr) | |||
5402 | return ToTPListOrErr.takeError(); | |||
5403 | ||||
5404 | PartVarSpecDecl *ToPartial; | |||
5405 | if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC, | |||
5406 | *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, | |||
5407 | VarTemplate, T, *TInfoOrErr, | |||
5408 | D->getStorageClass(), TemplateArgs, ArgInfos)) | |||
5409 | return ToPartial; | |||
5410 | ||||
5411 | if (Expected<PartVarSpecDecl *> ToInstOrErr = import( | |||
5412 | FromPartial->getInstantiatedFromMember())) | |||
5413 | ToPartial->setInstantiatedFromMember(*ToInstOrErr); | |||
5414 | else | |||
5415 | return ToInstOrErr.takeError(); | |||
5416 | ||||
5417 | if (FromPartial->isMemberSpecialization()) | |||
5418 | ToPartial->setMemberSpecialization(); | |||
5419 | ||||
5420 | D2 = ToPartial; | |||
5421 | ||||
5422 | } else { // Full specialization | |||
5423 | if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, | |||
5424 | *BeginLocOrErr, *IdLocOrErr, VarTemplate, | |||
5425 | T, *TInfoOrErr, | |||
5426 | D->getStorageClass(), TemplateArgs)) | |||
5427 | return D2; | |||
5428 | } | |||
5429 | ||||
5430 | if (D->getPointOfInstantiation().isValid()) { | |||
5431 | if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation())) | |||
5432 | D2->setPointOfInstantiation(*POIOrErr); | |||
5433 | else | |||
5434 | return POIOrErr.takeError(); | |||
5435 | } | |||
5436 | ||||
5437 | D2->setSpecializationKind(D->getSpecializationKind()); | |||
5438 | D2->setTemplateArgsInfo(ToTAInfo); | |||
5439 | ||||
5440 | // Add this specialization to the class template. | |||
5441 | VarTemplate->AddSpecialization(D2, InsertPos); | |||
5442 | ||||
5443 | // Import the qualifier, if any. | |||
5444 | if (auto LocOrErr = import(D->getQualifierLoc())) | |||
5445 | D2->setQualifierInfo(*LocOrErr); | |||
5446 | else | |||
5447 | return LocOrErr.takeError(); | |||
5448 | ||||
5449 | if (D->isConstexpr()) | |||
5450 | D2->setConstexpr(true); | |||
5451 | ||||
5452 | // Add the specialization to this context. | |||
5453 | D2->setLexicalDeclContext(LexicalDC); | |||
5454 | LexicalDC->addDeclInternal(D2); | |||
5455 | ||||
5456 | D2->setAccess(D->getAccess()); | |||
5457 | } | |||
5458 | ||||
5459 | if (Error Err = ImportInitializer(D, D2)) | |||
5460 | return std::move(Err); | |||
5461 | ||||
5462 | return D2; | |||
5463 | } | |||
5464 | ||||
5465 | ExpectedDecl | |||
5466 | ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { | |||
5467 | DeclContext *DC, *LexicalDC; | |||
5468 | DeclarationName Name; | |||
5469 | SourceLocation Loc; | |||
5470 | NamedDecl *ToD; | |||
5471 | ||||
5472 | if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) | |||
5473 | return std::move(Err); | |||
5474 | ||||
5475 | if (ToD) | |||
5476 | return ToD; | |||
5477 | ||||
5478 | const FunctionTemplateDecl *FoundByLookup = nullptr; | |||
5479 | ||||
5480 | // Try to find a function in our own ("to") context with the same name, same | |||
5481 | // type, and in the same context as the function we're importing. | |||
5482 | // FIXME Split this into a separate function. | |||
5483 | if (!LexicalDC->isFunctionOrMethod()) { | |||
5484 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; | |||
5485 | auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); | |||
5486 | for (auto *FoundDecl : FoundDecls) { | |||
5487 | if (!FoundDecl->isInIdentifierNamespace(IDNS)) | |||
5488 | continue; | |||
5489 | ||||
5490 | if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) { | |||
5491 | if (FoundTemplate->hasExternalFormalLinkage() && | |||
5492 | D->hasExternalFormalLinkage()) { | |||
5493 | if (IsStructuralMatch(D, FoundTemplate)) { | |||
5494 | FunctionTemplateDecl *TemplateWithDef = | |||
5495 | getTemplateDefinition(FoundTemplate); | |||
5496 | if (D->isThisDeclarationADefinition() && TemplateWithDef) { | |||
5497 | return Importer.MapImported(D, TemplateWithDef); | |||
5498 | } | |||
5499 | FoundByLookup = FoundTemplate; | |||
5500 | break; | |||
5501 | } | |||
5502 | // TODO: handle conflicting names | |||
5503 | } | |||
5504 | } | |||
5505 | } | |||
5506 | } | |||
5507 | ||||
5508 | auto ParamsOrErr = import(D->getTemplateParameters()); | |||
5509 | if (!ParamsOrErr) | |||
5510 | return ParamsOrErr.takeError(); | |||
5511 | ||||
5512 | FunctionDecl *TemplatedFD; | |||
5513 | if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl())) | |||
5514 | return std::move(Err); | |||
5515 | ||||
5516 | FunctionTemplateDecl *ToFunc; | |||
5517 | if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name, | |||
5518 | *ParamsOrErr, TemplatedFD)) | |||
5519 | return ToFunc; | |||
5520 | ||||
5521 | TemplatedFD->setDescribedFunctionTemplate(ToFunc); | |||
5522 | ||||
5523 | ToFunc->setAccess(D->getAccess()); | |||
5524 | ToFunc->setLexicalDeclContext(LexicalDC); | |||
5525 | LexicalDC->addDeclInternal(ToFunc); | |||
5526 | ||||
5527 | if (FoundByLookup) { | |||
5528 | auto *Recent = | |||
5529 | const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl()); | |||
5530 | if (!TemplatedFD->getPreviousDecl()) { | |||
5531 | assert(FoundByLookup->getTemplatedDecl() &&((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set" ) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 5532, __PRETTY_FUNCTION__)) | |||
5532 | "Found decl must have its templated decl set")((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set" ) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 5532, __PRETTY_FUNCTION__)); | |||
5533 | auto *PrevTemplated = | |||
5534 | FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); | |||
5535 | if (TemplatedFD != PrevTemplated) | |||
5536 | TemplatedFD->setPreviousDecl(PrevTemplated); | |||
5537 | } | |||
5538 | ToFunc->setPreviousDecl(Recent); | |||
5539 | } | |||
5540 | ||||
5541 | return ToFunc; | |||
5542 | } | |||
5543 | ||||
5544 | //---------------------------------------------------------------------------- | |||
5545 | // Import Statements | |||
5546 | //---------------------------------------------------------------------------- | |||
5547 | ||||
5548 | ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) { | |||
5549 | Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node) | |||
5550 | << S->getStmtClassName(); | |||
5551 | return make_error<ImportError>(ImportError::UnsupportedConstruct); | |||
5552 | } | |||
5553 | ||||
5554 | ||||
5555 | ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) { | |||
5556 | SmallVector<IdentifierInfo *, 4> Names; | |||
5557 | for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { | |||
5558 | IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I)); | |||
5559 | // ToII is nullptr when no symbolic name is given for output operand | |||
5560 | // see ParseStmtAsm::ParseAsmOperandsOpt | |||
5561 | Names.push_back(ToII); | |||
5562 | } | |||
5563 | ||||
5564 | for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { | |||
5565 | IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I)); | |||
5566 | // ToII is nullptr when no symbolic name is given for input operand | |||
5567 | // see ParseStmtAsm::ParseAsmOperandsOpt | |||
5568 | Names.push_back(ToII); | |||
5569 | } | |||
5570 | ||||
5571 | SmallVector<StringLiteral *, 4> Clobbers; | |||
5572 | for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) { | |||
5573 | if (auto ClobberOrErr = import(S->getClobberStringLiteral(I))) | |||
5574 | Clobbers.push_back(*ClobberOrErr); | |||
5575 | else | |||
5576 | return ClobberOrErr.takeError(); | |||
5577 | ||||
5578 | } | |||
5579 | ||||
5580 | SmallVector<StringLiteral *, 4> Constraints; | |||
5581 | for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { | |||
5582 | if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I))) | |||
5583 | Constraints.push_back(*OutputOrErr); | |||
5584 | else | |||
5585 | return OutputOrErr.takeError(); | |||
5586 | } | |||
5587 | ||||
5588 | for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { | |||
5589 | if (auto InputOrErr = import(S->getInputConstraintLiteral(I))) | |||
5590 | Constraints.push_back(*InputOrErr); | |||
5591 | else | |||
5592 | return InputOrErr.takeError(); | |||
5593 | } | |||
5594 | ||||
5595 | SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() + | |||
5596 | S->getNumLabels()); | |||
5597 | if (Error Err = ImportContainerChecked(S->outputs(), Exprs)) | |||
5598 | return std::move(Err); | |||
5599 | ||||
5600 | if (Error Err = | |||
5601 | ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs())) | |||
5602 | return std::move(Err); | |||
5603 | ||||
5604 | if (Error Err = ImportArrayChecked( | |||
5605 | S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs())) | |||
5606 | return std::move(Err); | |||
5607 | ||||
5608 | ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc()); | |||
5609 | if (!AsmLocOrErr) | |||
5610 | return AsmLocOrErr.takeError(); | |||
5611 | auto AsmStrOrErr = import(S->getAsmString()); | |||
5612 | if (!AsmStrOrErr) | |||
5613 | return AsmStrOrErr.takeError(); | |||
5614 | ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc()); | |||
5615 | if (!RParenLocOrErr) | |||
5616 | return RParenLocOrErr.takeError(); | |||
5617 | ||||
5618 | return new (Importer.getToContext()) GCCAsmStmt( | |||
5619 | Importer.getToContext(), | |||
5620 | *AsmLocOrErr, | |||
5621 | S->isSimple(), | |||
5622 | S->isVolatile(), | |||
5623 | S->getNumOutputs(), | |||
5624 | S->getNumInputs(), | |||
5625 | Names.data(), | |||
5626 | Constraints.data(), | |||
5627 | Exprs.data(), | |||
5628 | *AsmStrOrErr, | |||
5629 | S->getNumClobbers(), | |||
5630 | Clobbers.data(), | |||
5631 | S->getNumLabels(), | |||
5632 | *RParenLocOrErr); | |||
5633 | } | |||
5634 | ||||
5635 | ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) { | |||
5636 | auto Imp = importSeq(S->getDeclGroup(), S->getBeginLoc(), S->getEndLoc()); | |||
5637 | if (!Imp) | |||
5638 | return Imp.takeError(); | |||
5639 | ||||
5640 | DeclGroupRef ToDG; | |||
5641 | SourceLocation ToBeginLoc, ToEndLoc; | |||
5642 | std::tie(ToDG, ToBeginLoc, ToEndLoc) = *Imp; | |||
5643 | ||||
5644 | return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc); | |||
5645 | } | |||
5646 | ||||
5647 | ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) { | |||
5648 | ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc()); | |||
5649 | if (!ToSemiLocOrErr) | |||
5650 | return ToSemiLocOrErr.takeError(); | |||
5651 | return new (Importer.getToContext()) NullStmt( | |||
5652 | *ToSemiLocOrErr, S->hasLeadingEmptyMacro()); | |||
5653 | } | |||
5654 | ||||
5655 | ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) { | |||
5656 | SmallVector<Stmt *, 8> ToStmts(S->size()); | |||
5657 | ||||
5658 | if (Error Err = ImportContainerChecked(S->body(), ToStmts)) | |||
5659 | return std::move(Err); | |||
5660 | ||||
5661 | ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc()); | |||
5662 | if (!ToLBracLocOrErr) | |||
5663 | return ToLBracLocOrErr.takeError(); | |||
5664 | ||||
5665 | ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc()); | |||
5666 | if (!ToRBracLocOrErr) | |||
5667 | return ToRBracLocOrErr.takeError(); | |||
5668 | ||||
5669 | return CompoundStmt::Create( | |||
5670 | Importer.getToContext(), ToStmts, | |||
5671 | *ToLBracLocOrErr, *ToRBracLocOrErr); | |||
5672 | } | |||
5673 | ||||
5674 | ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) { | |||
5675 | auto Imp = importSeq( | |||
5676 | S->getLHS(), S->getRHS(), S->getSubStmt(), S->getCaseLoc(), | |||
5677 | S->getEllipsisLoc(), S->getColonLoc()); | |||
5678 | if (!Imp) | |||
5679 | return Imp.takeError(); | |||
5680 | ||||
5681 | Expr *ToLHS, *ToRHS; | |||
5682 | Stmt *ToSubStmt; | |||
5683 | SourceLocation ToCaseLoc, ToEllipsisLoc, ToColonLoc; | |||
5684 | std::tie(ToLHS, ToRHS, ToSubStmt, ToCaseLoc, ToEllipsisLoc, ToColonLoc) = | |||
5685 | *Imp; | |||
5686 | ||||
5687 | auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS, | |||
5688 | ToCaseLoc, ToEllipsisLoc, ToColonLoc); | |||
5689 | ToStmt->setSubStmt(ToSubStmt); | |||
5690 | ||||
5691 | return ToStmt; | |||
5692 | } | |||
5693 | ||||
5694 | ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) { | |||
5695 | auto Imp = importSeq(S->getDefaultLoc(), S->getColonLoc(), S->getSubStmt()); | |||
5696 | if (!Imp) | |||
5697 | return Imp.takeError(); | |||
5698 | ||||
5699 | SourceLocation ToDefaultLoc, ToColonLoc; | |||
5700 | Stmt *ToSubStmt; | |||
5701 | std::tie(ToDefaultLoc, ToColonLoc, ToSubStmt) = *Imp; | |||
5702 | ||||
5703 | return new (Importer.getToContext()) DefaultStmt( | |||
5704 | ToDefaultLoc, ToColonLoc, ToSubStmt); | |||
5705 | } | |||
5706 | ||||
5707 | ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) { | |||
5708 | auto Imp = importSeq(S->getIdentLoc(), S->getDecl(), S->getSubStmt()); | |||
5709 | if (!Imp) | |||
5710 | return Imp.takeError(); | |||
5711 | ||||
5712 | SourceLocation ToIdentLoc; | |||
5713 | LabelDecl *ToLabelDecl; | |||
5714 | Stmt *ToSubStmt; | |||
5715 | std::tie(ToIdentLoc, ToLabelDecl, ToSubStmt) = *Imp; | |||
5716 | ||||
5717 | return new (Importer.getToContext()) LabelStmt( | |||
5718 | ToIdentLoc, ToLabelDecl, ToSubStmt); | |||
5719 | } | |||
5720 | ||||
5721 | ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) { | |||
5722 | ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc()); | |||
5723 | if (!ToAttrLocOrErr) | |||
5724 | return ToAttrLocOrErr.takeError(); | |||
5725 | ArrayRef<const Attr*> FromAttrs(S->getAttrs()); | |||
5726 | SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size()); | |||
5727 | if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs)) | |||
5728 | return std::move(Err); | |||
5729 | ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); | |||
5730 | if (!ToSubStmtOrErr) | |||
5731 | return ToSubStmtOrErr.takeError(); | |||
5732 | ||||
5733 | return AttributedStmt::Create( | |||
5734 | Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr); | |||
5735 | } | |||
5736 | ||||
5737 | ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) { | |||
5738 | auto Imp = importSeq( | |||
5739 | S->getIfLoc(), S->getInit(), S->getConditionVariable(), S->getCond(), | |||
5740 | S->getThen(), S->getElseLoc(), S->getElse()); | |||
5741 | if (!Imp) | |||
5742 | return Imp.takeError(); | |||
5743 | ||||
5744 | SourceLocation ToIfLoc, ToElseLoc; | |||
5745 | Stmt *ToInit, *ToThen, *ToElse; | |||
5746 | VarDecl *ToConditionVariable; | |||
5747 | Expr *ToCond; | |||
5748 | std::tie( | |||
5749 | ToIfLoc, ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc, ToElse) = | |||
5750 | *Imp; | |||
5751 | ||||
5752 | return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->isConstexpr(), | |||
5753 | ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc, | |||
5754 | ToElse); | |||
5755 | } | |||
5756 | ||||
5757 | ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) { | |||
5758 | auto Imp = importSeq( | |||
5759 | S->getInit(), S->getConditionVariable(), S->getCond(), | |||
5760 | S->getBody(), S->getSwitchLoc()); | |||
5761 | if (!Imp) | |||
5762 | return Imp.takeError(); | |||
5763 | ||||
5764 | Stmt *ToInit, *ToBody; | |||
5765 | VarDecl *ToConditionVariable; | |||
5766 | Expr *ToCond; | |||
5767 | SourceLocation ToSwitchLoc; | |||
5768 | std::tie(ToInit, ToConditionVariable, ToCond, ToBody, ToSwitchLoc) = *Imp; | |||
5769 | ||||
5770 | auto *ToStmt = SwitchStmt::Create(Importer.getToContext(), ToInit, | |||
5771 | ToConditionVariable, ToCond); | |||
5772 | ToStmt->setBody(ToBody); | |||
5773 | ToStmt->setSwitchLoc(ToSwitchLoc); | |||
5774 | ||||
5775 | // Now we have to re-chain the cases. | |||
5776 | SwitchCase *LastChainedSwitchCase = nullptr; | |||
5777 | for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr; | |||
5778 | SC = SC->getNextSwitchCase()) { | |||
5779 | Expected<SwitchCase *> ToSCOrErr = import(SC); | |||
5780 | if (!ToSCOrErr) | |||
5781 | return ToSCOrErr.takeError(); | |||
5782 | if (LastChainedSwitchCase) | |||
5783 | LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr); | |||
5784 | else | |||
5785 | ToStmt->setSwitchCaseList(*ToSCOrErr); | |||
5786 | LastChainedSwitchCase = *ToSCOrErr; | |||
5787 | } | |||
5788 | ||||
5789 | return ToStmt; | |||
5790 | } | |||
5791 | ||||
5792 | ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) { | |||
5793 | auto Imp = importSeq( | |||
5794 | S->getConditionVariable(), S->getCond(), S->getBody(), S->getWhileLoc()); | |||
5795 | if (!Imp) | |||
5796 | return Imp.takeError(); | |||
5797 | ||||
5798 | VarDecl *ToConditionVariable; | |||
5799 | Expr *ToCond; | |||
5800 | Stmt *ToBody; | |||
5801 | SourceLocation ToWhileLoc; | |||
5802 | std::tie(ToConditionVariable, ToCond, ToBody, ToWhileLoc) = *Imp; | |||
5803 | ||||
5804 | return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond, | |||
5805 | ToBody, ToWhileLoc); | |||
5806 | } | |||
5807 | ||||
5808 | ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) { | |||
5809 | auto Imp = importSeq( | |||
5810 | S->getBody(), S->getCond(), S->getDoLoc(), S->getWhileLoc(), | |||
5811 | S->getRParenLoc()); | |||
5812 | if (!Imp) | |||
5813 | return Imp.takeError(); | |||
5814 | ||||
5815 | Stmt *ToBody; | |||
5816 | Expr *ToCond; | |||
5817 | SourceLocation ToDoLoc, ToWhileLoc, ToRParenLoc; | |||
5818 | std::tie(ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc) = *Imp; | |||
5819 | ||||
5820 | return new (Importer.getToContext()) DoStmt( | |||
5821 | ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc); | |||
5822 | } | |||
5823 | ||||
5824 | ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) { | |||
5825 | auto Imp = importSeq( | |||
5826 | S->getInit(), S->getCond(), S->getConditionVariable(), S->getInc(), | |||
5827 | S->getBody(), S->getForLoc(), S->getLParenLoc(), S->getRParenLoc()); | |||
5828 | if (!Imp) | |||
5829 | return Imp.takeError(); | |||
5830 | ||||
5831 | Stmt *ToInit; | |||
5832 | Expr *ToCond, *ToInc; | |||
5833 | VarDecl *ToConditionVariable; | |||
5834 | Stmt *ToBody; | |||
5835 | SourceLocation ToForLoc, ToLParenLoc, ToRParenLoc; | |||
5836 | std::tie( | |||
5837 | ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, | |||
5838 | ToLParenLoc, ToRParenLoc) = *Imp; | |||
5839 | ||||
5840 | return new (Importer.getToContext()) ForStmt( | |||
5841 | Importer.getToContext(), | |||
5842 | ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc, | |||
5843 | ToRParenLoc); | |||
5844 | } | |||
5845 | ||||
5846 | ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) { | |||
5847 | auto Imp = importSeq(S->getLabel(), S->getGotoLoc(), S->getLabelLoc()); | |||
5848 | if (!Imp) | |||
5849 | return Imp.takeError(); | |||
5850 | ||||
5851 | LabelDecl *ToLabel; | |||
5852 | SourceLocation ToGotoLoc, ToLabelLoc; | |||
5853 | std::tie(ToLabel, ToGotoLoc, ToLabelLoc) = *Imp; | |||
5854 | ||||
5855 | return new (Importer.getToContext()) GotoStmt( | |||
5856 | ToLabel, ToGotoLoc, ToLabelLoc); | |||
5857 | } | |||
5858 | ||||
5859 | ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) { | |||
5860 | auto Imp = importSeq(S->getGotoLoc(), S->getStarLoc(), S->getTarget()); | |||
5861 | if (!Imp) | |||
5862 | return Imp.takeError(); | |||
5863 | ||||
5864 | SourceLocation ToGotoLoc, ToStarLoc; | |||
5865 | Expr *ToTarget; | |||
5866 | std::tie(ToGotoLoc, ToStarLoc, ToTarget) = *Imp; | |||
5867 | ||||
5868 | return new (Importer.getToContext()) IndirectGotoStmt( | |||
5869 | ToGotoLoc, ToStarLoc, ToTarget); | |||
5870 | } | |||
5871 | ||||
5872 | ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) { | |||
5873 | ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc()); | |||
5874 | if (!ToContinueLocOrErr) | |||
5875 | return ToContinueLocOrErr.takeError(); | |||
5876 | return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr); | |||
5877 | } | |||
5878 | ||||
5879 | ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) { | |||
5880 | auto ToBreakLocOrErr = import(S->getBreakLoc()); | |||
5881 | if (!ToBreakLocOrErr) | |||
5882 | return ToBreakLocOrErr.takeError(); | |||
5883 | return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr); | |||
5884 | } | |||
5885 | ||||
5886 | ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) { | |||
5887 | auto Imp = importSeq( | |||
5888 | S->getReturnLoc(), S->getRetValue(), S->getNRVOCandidate()); | |||
5889 | if (!Imp) | |||
5890 | return Imp.takeError(); | |||
5891 | ||||
5892 | SourceLocation ToReturnLoc; | |||
5893 | Expr *ToRetValue; | |||
5894 | const VarDecl *ToNRVOCandidate; | |||
5895 | std::tie(ToReturnLoc, ToRetValue, ToNRVOCandidate) = *Imp; | |||
5896 | ||||
5897 | return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue, | |||
5898 | ToNRVOCandidate); | |||
5899 | } | |||
5900 | ||||
5901 | ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) { | |||
5902 | auto Imp = importSeq( | |||
5903 | S->getCatchLoc(), S->getExceptionDecl(), S->getHandlerBlock()); | |||
5904 | if (!Imp) | |||
5905 | return Imp.takeError(); | |||
5906 | ||||
5907 | SourceLocation ToCatchLoc; | |||
5908 | VarDecl *ToExceptionDecl; | |||
5909 | Stmt *ToHandlerBlock; | |||
5910 | std::tie(ToCatchLoc, ToExceptionDecl, ToHandlerBlock) = *Imp; | |||
5911 | ||||
5912 | return new (Importer.getToContext()) CXXCatchStmt ( | |||
5913 | ToCatchLoc, ToExceptionDecl, ToHandlerBlock); | |||
5914 | } | |||
5915 | ||||
5916 | ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) { | |||
5917 | ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc()); | |||
5918 | if (!ToTryLocOrErr) | |||
5919 | return ToTryLocOrErr.takeError(); | |||
5920 | ||||
5921 | ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock()); | |||
5922 | if (!ToTryBlockOrErr) | |||
5923 | return ToTryBlockOrErr.takeError(); | |||
5924 | ||||
5925 | SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers()); | |||
5926 | for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) { | |||
5927 | CXXCatchStmt *FromHandler = S->getHandler(HI); | |||
5928 | if (auto ToHandlerOrErr = import(FromHandler)) | |||
5929 | ToHandlers[HI] = *ToHandlerOrErr; | |||
5930 | else | |||
5931 | return ToHandlerOrErr.takeError(); | |||
5932 | } | |||
5933 | ||||
5934 | return CXXTryStmt::Create( | |||
5935 | Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers); | |||
5936 | } | |||
5937 | ||||
5938 | ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) { | |||
5939 | auto Imp1 = importSeq( | |||
5940 | S->getInit(), S->getRangeStmt(), S->getBeginStmt(), S->getEndStmt(), | |||
5941 | S->getCond(), S->getInc(), S->getLoopVarStmt(), S->getBody()); | |||
5942 | if (!Imp1) | |||
5943 | return Imp1.takeError(); | |||
5944 | auto Imp2 = importSeq( | |||
5945 | S->getForLoc(), S->getCoawaitLoc(), S->getColonLoc(), S->getRParenLoc()); | |||
5946 | if (!Imp2) | |||
5947 | return Imp2.takeError(); | |||
5948 | ||||
5949 | DeclStmt *ToRangeStmt, *ToBeginStmt, *ToEndStmt, *ToLoopVarStmt; | |||
5950 | Expr *ToCond, *ToInc; | |||
5951 | Stmt *ToInit, *ToBody; | |||
5952 | std::tie( | |||
5953 | ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt, | |||
5954 | ToBody) = *Imp1; | |||
5955 | SourceLocation ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc; | |||
5956 | std::tie(ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc) = *Imp2; | |||
5957 | ||||
5958 | return new (Importer.getToContext()) CXXForRangeStmt( | |||
5959 | ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt, | |||
5960 | ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc); | |||
5961 | } | |||
5962 | ||||
5963 | ExpectedStmt | |||
5964 | ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { | |||
5965 | auto Imp = importSeq( | |||
5966 | S->getElement(), S->getCollection(), S->getBody(), | |||
5967 | S->getForLoc(), S->getRParenLoc()); | |||
5968 | if (!Imp) | |||
5969 | return Imp.takeError(); | |||
5970 | ||||
5971 | Stmt *ToElement, *ToBody; | |||
5972 | Expr *ToCollection; | |||
5973 | SourceLocation ToForLoc, ToRParenLoc; | |||
5974 | std::tie(ToElement, ToCollection, ToBody, ToForLoc, ToRParenLoc) = *Imp; | |||
5975 | ||||
5976 | return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement, | |||
5977 | ToCollection, | |||
5978 | ToBody, | |||
5979 | ToForLoc, | |||
5980 | ToRParenLoc); | |||
5981 | } | |||
5982 | ||||
5983 | ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { | |||
5984 | auto Imp = importSeq( | |||
5985 | S->getAtCatchLoc(), S->getRParenLoc(), S->getCatchParamDecl(), | |||
5986 | S->getCatchBody()); | |||
5987 | if (!Imp) | |||
5988 | return Imp.takeError(); | |||
5989 | ||||
5990 | SourceLocation ToAtCatchLoc, ToRParenLoc; | |||
5991 | VarDecl *ToCatchParamDecl; | |||
5992 | Stmt *ToCatchBody; | |||
5993 | std::tie(ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody) = *Imp; | |||
5994 | ||||
5995 | return new (Importer.getToContext()) ObjCAtCatchStmt ( | |||
5996 | ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody); | |||
5997 | } | |||
5998 | ||||
5999 | ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) { | |||
6000 | ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc()); | |||
6001 | if (!ToAtFinallyLocOrErr) | |||
6002 | return ToAtFinallyLocOrErr.takeError(); | |||
6003 | ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody()); | |||
6004 | if (!ToAtFinallyStmtOrErr) | |||
6005 | return ToAtFinallyStmtOrErr.takeError(); | |||
6006 | return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr, | |||
6007 | *ToAtFinallyStmtOrErr); | |||
6008 | } | |||
6009 | ||||
6010 | ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { | |||
6011 | auto Imp = importSeq( | |||
6012 | S->getAtTryLoc(), S->getTryBody(), S->getFinallyStmt()); | |||
6013 | if (!Imp) | |||
6014 | return Imp.takeError(); | |||
6015 | ||||
6016 | SourceLocation ToAtTryLoc; | |||
6017 | Stmt *ToTryBody, *ToFinallyStmt; | |||
6018 | std::tie(ToAtTryLoc, ToTryBody, ToFinallyStmt) = *Imp; | |||
6019 | ||||
6020 | SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts()); | |||
6021 | for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) { | |||
6022 | ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI); | |||
6023 | if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt)) | |||
6024 | ToCatchStmts[CI] = *ToCatchStmtOrErr; | |||
6025 | else | |||
6026 | return ToCatchStmtOrErr.takeError(); | |||
6027 | } | |||
6028 | ||||
6029 | return ObjCAtTryStmt::Create(Importer.getToContext(), | |||
6030 | ToAtTryLoc, ToTryBody, | |||
6031 | ToCatchStmts.begin(), ToCatchStmts.size(), | |||
6032 | ToFinallyStmt); | |||
6033 | } | |||
6034 | ||||
6035 | ExpectedStmt ASTNodeImporter::VisitObjCAtSynchronizedStmt | |||
6036 | (ObjCAtSynchronizedStmt *S) { | |||
6037 | auto Imp = importSeq( | |||
6038 | S->getAtSynchronizedLoc(), S->getSynchExpr(), S->getSynchBody()); | |||
6039 | if (!Imp) | |||
6040 | return Imp.takeError(); | |||
6041 | ||||
6042 | SourceLocation ToAtSynchronizedLoc; | |||
6043 | Expr *ToSynchExpr; | |||
6044 | Stmt *ToSynchBody; | |||
6045 | std::tie(ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody) = *Imp; | |||
6046 | ||||
6047 | return new (Importer.getToContext()) ObjCAtSynchronizedStmt( | |||
6048 | ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody); | |||
6049 | } | |||
6050 | ||||
6051 | ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { | |||
6052 | ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc()); | |||
6053 | if (!ToThrowLocOrErr) | |||
6054 | return ToThrowLocOrErr.takeError(); | |||
6055 | ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr()); | |||
6056 | if (!ToThrowExprOrErr) | |||
6057 | return ToThrowExprOrErr.takeError(); | |||
6058 | return new (Importer.getToContext()) ObjCAtThrowStmt( | |||
6059 | *ToThrowLocOrErr, *ToThrowExprOrErr); | |||
6060 | } | |||
6061 | ||||
6062 | ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt( | |||
6063 | ObjCAutoreleasePoolStmt *S) { | |||
6064 | ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc()); | |||
6065 | if (!ToAtLocOrErr) | |||
6066 | return ToAtLocOrErr.takeError(); | |||
6067 | ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); | |||
6068 | if (!ToSubStmtOrErr) | |||
6069 | return ToSubStmtOrErr.takeError(); | |||
6070 | return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr, | |||
6071 | *ToSubStmtOrErr); | |||
6072 | } | |||
6073 | ||||
6074 | //---------------------------------------------------------------------------- | |||
6075 | // Import Expressions | |||
6076 | //---------------------------------------------------------------------------- | |||
6077 | ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) { | |||
6078 | Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node) | |||
6079 | << E->getStmtClassName(); | |||
6080 | return make_error<ImportError>(ImportError::UnsupportedConstruct); | |||
| ||||
6081 | } | |||
6082 | ||||
6083 | ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) { | |||
6084 | auto Imp = importSeq( | |||
6085 | E->getBuiltinLoc(), E->getSubExpr(), E->getWrittenTypeInfo(), | |||
6086 | E->getRParenLoc(), E->getType()); | |||
6087 | if (!Imp) | |||
6088 | return Imp.takeError(); | |||
6089 | ||||
6090 | SourceLocation ToBuiltinLoc, ToRParenLoc; | |||
6091 | Expr *ToSubExpr; | |||
6092 | TypeSourceInfo *ToWrittenTypeInfo; | |||
6093 | QualType ToType; | |||
6094 | std::tie(ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType) = | |||
6095 | *Imp; | |||
6096 | ||||
6097 | return new (Importer.getToContext()) VAArgExpr( | |||
6098 | ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType, | |||
6099 | E->isMicrosoftABI()); | |||
6100 | } | |||
6101 | ||||
6102 | ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) { | |||
6103 | auto Imp = importSeq(E->getCond(), E->getLHS(), E->getRHS(), | |||
6104 | E->getBuiltinLoc(), E->getRParenLoc(), E->getType()); | |||
6105 | if (!Imp) | |||
6106 | return Imp.takeError(); | |||
6107 | ||||
6108 | Expr *ToCond; | |||
6109 | Expr *ToLHS; | |||
6110 | Expr *ToRHS; | |||
6111 | SourceLocation ToBuiltinLoc, ToRParenLoc; | |||
6112 | QualType ToType; | |||
6113 | std::tie(ToCond, ToLHS, ToRHS, ToBuiltinLoc, ToRParenLoc, ToType) = *Imp; | |||
6114 | ||||
6115 | ExprValueKind VK = E->getValueKind(); | |||
6116 | ExprObjectKind OK = E->getObjectKind(); | |||
6117 | ||||
6118 | bool TypeDependent = ToCond->isTypeDependent(); | |||
6119 | bool ValueDependent = ToCond->isValueDependent(); | |||
6120 | ||||
6121 | // The value of CondIsTrue only matters if the value is not | |||
6122 | // condition-dependent. | |||
6123 | bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue(); | |||
6124 | ||||
6125 | return new (Importer.getToContext()) | |||
6126 | ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK, | |||
6127 | ToRParenLoc, CondIsTrue, TypeDependent, ValueDependent); | |||
6128 | } | |||
6129 | ||||
6130 | ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) { | |||
6131 | ExpectedType TypeOrErr = import(E->getType()); | |||
6132 | if (!TypeOrErr) | |||
6133 | return TypeOrErr.takeError(); | |||
6134 | ||||
6135 | ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc()); | |||
6136 | if (!BeginLocOrErr) | |||
6137 | return BeginLocOrErr.takeError(); | |||
6138 | ||||
6139 | return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr); | |||
6140 | } | |||
6141 | ||||
6142 | ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) { | |||
6143 | auto Imp = importSeq( | |||
6144 | E->getBeginLoc(), E->getType(), E->getFunctionName()); | |||
6145 | if (!Imp) | |||
6146 | return Imp.takeError(); | |||
6147 | ||||
6148 | SourceLocation ToBeginLoc; | |||
6149 | QualType ToType; | |||
6150 | StringLiteral *ToFunctionName; | |||
6151 | std::tie(ToBeginLoc, ToType, ToFunctionName) = *Imp; | |||
6152 | ||||
6153 | return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType, | |||
6154 | E->getIdentKind(), ToFunctionName); | |||
6155 | } | |||
6156 | ||||
6157 | ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { | |||
6158 | auto Imp = importSeq( | |||
6159 | E->getQualifierLoc(), E->getTemplateKeywordLoc(), E->getDecl(), | |||
6160 | E->getLocation(), E->getType()); | |||
6161 | if (!Imp) | |||
6162 | return Imp.takeError(); | |||
6163 | ||||
6164 | NestedNameSpecifierLoc ToQualifierLoc; | |||
6165 | SourceLocation ToTemplateKeywordLoc, ToLocation; | |||
6166 | ValueDecl *ToDecl; | |||
6167 | QualType ToType; | |||
6168 | std::tie(ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, ToLocation, ToType) = | |||
6169 | *Imp; | |||
6170 | ||||
6171 | NamedDecl *ToFoundD = nullptr; | |||
6172 | if (E->getDecl() != E->getFoundDecl()) { | |||
6173 | auto FoundDOrErr = import(E->getFoundDecl()); | |||
6174 | if (!FoundDOrErr) | |||
6175 | return FoundDOrErr.takeError(); | |||
6176 | ToFoundD = *FoundDOrErr; | |||
6177 | } | |||
6178 | ||||
6179 | TemplateArgumentListInfo ToTAInfo; | |||
6180 | TemplateArgumentListInfo *ToResInfo = nullptr; | |||
6181 | if (E->hasExplicitTemplateArgs()) { | |||
6182 | if (Error Err = | |||
6183 | ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) | |||
6184 | return std::move(Err); | |||
6185 | ToResInfo = &ToTAInfo; | |||
6186 | } | |||
6187 | ||||
6188 | auto *ToE = DeclRefExpr::Create( | |||
6189 | Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, | |||
6190 | E->refersToEnclosingVariableOrCapture(), ToLocation, ToType, | |||
6191 | E->getValueKind(), ToFoundD, ToResInfo); | |||
6192 | if (E->hadMultipleCandidates()) | |||
6193 | ToE->setHadMultipleCandidates(true); | |||
6194 | return ToE; | |||
6195 | } | |||
6196 | ||||
6197 | ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { | |||
6198 | ExpectedType TypeOrErr = import(E->getType()); | |||
6199 | if (!TypeOrErr) | |||
6200 | return TypeOrErr.takeError(); | |||
6201 | ||||
6202 | return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr); | |||
6203 | } | |||
6204 | ||||
6205 | ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) { | |||
6206 | ExpectedExpr ToInitOrErr = import(E->getInit()); | |||
6207 | if (!ToInitOrErr) | |||
6208 | return ToInitOrErr.takeError(); | |||
6209 | ||||
6210 | ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc()); | |||
6211 | if (!ToEqualOrColonLocOrErr) | |||
6212 | return ToEqualOrColonLocOrErr.takeError(); | |||
6213 | ||||
6214 | SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1); | |||
6215 | // List elements from the second, the first is Init itself | |||
6216 | for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) { | |||
6217 | if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I))) | |||
6218 | ToIndexExprs[I - 1] = *ToArgOrErr; | |||
6219 | else | |||
6220 | return ToArgOrErr.takeError(); | |||
6221 | } | |||
6222 | ||||
6223 | SmallVector<Designator, 4> ToDesignators(E->size()); | |||
6224 | if (Error Err = ImportContainerChecked(E->designators(), ToDesignators)) | |||
6225 | return std::move(Err); | |||
6226 | ||||
6227 | return DesignatedInitExpr::Create( | |||
6228 | Importer.getToContext(), ToDesignators, | |||
6229 | ToIndexExprs, *ToEqualOrColonLocOrErr, | |||
6230 | E->usesGNUSyntax(), *ToInitOrErr); | |||
6231 | } | |||
6232 | ||||
6233 | ExpectedStmt | |||
6234 | ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) { | |||
6235 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
6236 | if (!ToTypeOrErr) | |||
6237 | return ToTypeOrErr.takeError(); | |||
6238 | ||||
6239 | ExpectedSLoc ToLocationOrErr = import(E->getLocation()); | |||
6240 | if (!ToLocationOrErr) | |||
6241 | return ToLocationOrErr.takeError(); | |||
6242 | ||||
6243 | return new (Importer.getToContext()) CXXNullPtrLiteralExpr( | |||
6244 | *ToTypeOrErr, *ToLocationOrErr); | |||
6245 | } | |||
6246 | ||||
6247 | ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { | |||
6248 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
6249 | if (!ToTypeOrErr) | |||
6250 | return ToTypeOrErr.takeError(); | |||
6251 | ||||
6252 | ExpectedSLoc ToLocationOrErr = import(E->getLocation()); | |||
6253 | if (!ToLocationOrErr) | |||
6254 | return ToLocationOrErr.takeError(); | |||
6255 | ||||
6256 | return IntegerLiteral::Create( | |||
6257 | Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr); | |||
6258 | } | |||
6259 | ||||
6260 | ||||
6261 | ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) { | |||
6262 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
6263 | if (!ToTypeOrErr) | |||
6264 | return ToTypeOrErr.takeError(); | |||
6265 | ||||
6266 | ExpectedSLoc ToLocationOrErr = import(E->getLocation()); | |||
6267 | if (!ToLocationOrErr) | |||
6268 | return ToLocationOrErr.takeError(); | |||
6269 | ||||
6270 | return FloatingLiteral::Create( | |||
6271 | Importer.getToContext(), E->getValue(), E->isExact(), | |||
6272 | *ToTypeOrErr, *ToLocationOrErr); | |||
6273 | } | |||
6274 | ||||
6275 | ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) { | |||
6276 | auto ToTypeOrErr = import(E->getType()); | |||
6277 | if (!ToTypeOrErr) | |||
6278 | return ToTypeOrErr.takeError(); | |||
6279 | ||||
6280 | ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); | |||
6281 | if (!ToSubExprOrErr) | |||
6282 | return ToSubExprOrErr.takeError(); | |||
6283 | ||||
6284 | return new (Importer.getToContext()) ImaginaryLiteral( | |||
6285 | *ToSubExprOrErr, *ToTypeOrErr); | |||
6286 | } | |||
6287 | ||||
6288 | ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) { | |||
6289 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
6290 | if (!ToTypeOrErr) | |||
6291 | return ToTypeOrErr.takeError(); | |||
6292 | ||||
6293 | ExpectedSLoc ToLocationOrErr = import(E->getLocation()); | |||
6294 | if (!ToLocationOrErr) | |||
6295 | return ToLocationOrErr.takeError(); | |||
6296 | ||||
6297 | return new (Importer.getToContext()) CharacterLiteral( | |||
6298 | E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr); | |||
6299 | } | |||
6300 | ||||
6301 | ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) { | |||
6302 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
6303 | if (!ToTypeOrErr) | |||
6304 | return ToTypeOrErr.takeError(); | |||
6305 | ||||
6306 | SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated()); | |||
6307 | if (Error Err = ImportArrayChecked( | |||
6308 | E->tokloc_begin(), E->tokloc_end(), ToLocations.begin())) | |||
6309 | return std::move(Err); | |||
6310 | ||||
6311 | return StringLiteral::Create( | |||
6312 | Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(), | |||
6313 | *ToTypeOrErr, ToLocations.data(), ToLocations.size()); | |||
6314 | } | |||
6315 | ||||
6316 | ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { | |||
6317 | auto Imp = importSeq( | |||
6318 | E->getLParenLoc(), E->getTypeSourceInfo(), E->getType(), | |||
6319 | E->getInitializer()); | |||
6320 | if (!Imp) | |||
6321 | return Imp.takeError(); | |||
6322 | ||||
6323 | SourceLocation ToLParenLoc; | |||
6324 | TypeSourceInfo *ToTypeSourceInfo; | |||
6325 | QualType ToType; | |||
6326 | Expr *ToInitializer; | |||
6327 | std::tie(ToLParenLoc, ToTypeSourceInfo, ToType, ToInitializer) = *Imp; | |||
6328 | ||||
6329 | return new (Importer.getToContext()) CompoundLiteralExpr( | |||
6330 | ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(), | |||
6331 | ToInitializer, E->isFileScope()); | |||
6332 | } | |||
6333 | ||||
6334 | ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) { | |||
6335 | auto Imp = importSeq( | |||
6336 | E->getBuiltinLoc(), E->getType(), E->getRParenLoc()); | |||
6337 | if (!Imp) | |||
6338 | return Imp.takeError(); | |||
6339 | ||||
6340 | SourceLocation ToBuiltinLoc, ToRParenLoc; | |||
6341 | QualType ToType; | |||
6342 | std::tie(ToBuiltinLoc, ToType, ToRParenLoc) = *Imp; | |||
6343 | ||||
6344 | SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs()); | |||
6345 | if (Error Err = ImportArrayChecked( | |||
6346 | E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(), | |||
6347 | ToExprs.begin())) | |||
6348 | return std::move(Err); | |||
6349 | ||||
6350 | return new (Importer.getToContext()) AtomicExpr( | |||
6351 | ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc); | |||
6352 | } | |||
6353 | ||||
6354 | ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) { | |||
6355 | auto Imp = importSeq( | |||
6356 | E->getAmpAmpLoc(), E->getLabelLoc(), E->getLabel(), E->getType()); | |||
6357 | if (!Imp) | |||
6358 | return Imp.takeError(); | |||
6359 | ||||
6360 | SourceLocation ToAmpAmpLoc, ToLabelLoc; | |||
6361 | LabelDecl *ToLabel; | |||
6362 | QualType ToType; | |||
6363 | std::tie(ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType) = *Imp; | |||
6364 | ||||
6365 | return new (Importer.getToContext()) AddrLabelExpr( | |||
6366 | ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType); | |||
6367 | } | |||
6368 | ||||
6369 | ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) { | |||
6370 | auto Imp = importSeq(E->getSubExpr()); | |||
6371 | if (!Imp) | |||
6372 | return Imp.takeError(); | |||
6373 | ||||
6374 | Expr *ToSubExpr; | |||
6375 | std::tie(ToSubExpr) = *Imp; | |||
6376 | ||||
6377 | return ConstantExpr::Create(Importer.getToContext(), ToSubExpr); | |||
6378 | } | |||
6379 | ||||
6380 | ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) { | |||
6381 | auto Imp = importSeq(E->getLParen(), E->getRParen(), E->getSubExpr()); | |||
6382 | if (!Imp) | |||
6383 | return Imp.takeError(); | |||
6384 | ||||
6385 | SourceLocation ToLParen, ToRParen; | |||
6386 | Expr *ToSubExpr; | |||
6387 | std::tie(ToLParen, ToRParen, ToSubExpr) = *Imp; | |||
6388 | ||||
6389 | return new (Importer.getToContext()) | |||
6390 | ParenExpr(ToLParen, ToRParen, ToSubExpr); | |||
6391 | } | |||
6392 | ||||
6393 | ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) { | |||
6394 | SmallVector<Expr *, 4> ToExprs(E->getNumExprs()); | |||
6395 | if (Error Err = ImportContainerChecked(E->exprs(), ToExprs)) | |||
6396 | return std::move(Err); | |||
6397 | ||||
6398 | ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc()); | |||
6399 | if (!ToLParenLocOrErr) | |||
6400 | return ToLParenLocOrErr.takeError(); | |||
6401 | ||||
6402 | ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc()); | |||
6403 | if (!ToRParenLocOrErr) | |||
6404 | return ToRParenLocOrErr.takeError(); | |||
6405 | ||||
6406 | return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr, | |||
6407 | ToExprs, *ToRParenLocOrErr); | |||
6408 | } | |||
6409 | ||||
6410 | ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) { | |||
6411 | auto Imp = importSeq( | |||
6412 | E->getSubStmt(), E->getType(), E->getLParenLoc(), E->getRParenLoc()); | |||
6413 | if (!Imp) | |||
6414 | return Imp.takeError(); | |||
6415 | ||||
6416 | CompoundStmt *ToSubStmt; | |||
6417 | QualType ToType; | |||
6418 | SourceLocation ToLParenLoc, ToRParenLoc; | |||
6419 | std::tie(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc) = *Imp; | |||
6420 | ||||
6421 | return new (Importer.getToContext()) StmtExpr( | |||
6422 | ToSubStmt, ToType, ToLParenLoc, ToRParenLoc); | |||
6423 | } | |||
6424 | ||||
6425 | ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { | |||
6426 | auto Imp = importSeq( | |||
6427 | E->getSubExpr(), E->getType(), E->getOperatorLoc()); | |||
6428 | if (!Imp) | |||
6429 | return Imp.takeError(); | |||
6430 | ||||
6431 | Expr *ToSubExpr; | |||
6432 | QualType ToType; | |||
6433 | SourceLocation ToOperatorLoc; | |||
6434 | std::tie(ToSubExpr, ToType, ToOperatorLoc) = *Imp; | |||
6435 | ||||
6436 | return new (Importer.getToContext()) UnaryOperator( | |||
6437 | ToSubExpr, E->getOpcode(), ToType, E->getValueKind(), E->getObjectKind(), | |||
6438 | ToOperatorLoc, E->canOverflow()); | |||
6439 | } | |||
6440 | ||||
6441 | ExpectedStmt | |||
6442 | ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { | |||
6443 | auto Imp = importSeq(E->getType(), E->getOperatorLoc(), E->getRParenLoc()); | |||
6444 | if (!Imp) | |||
6445 | return Imp.takeError(); | |||
6446 | ||||
6447 | QualType ToType; | |||
6448 | SourceLocation ToOperatorLoc, ToRParenLoc; | |||
6449 | std::tie(ToType, ToOperatorLoc, ToRParenLoc) = *Imp; | |||
6450 | ||||
6451 | if (E->isArgumentType()) { | |||
6452 | Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr = | |||
6453 | import(E->getArgumentTypeInfo()); | |||
6454 | if (!ToArgumentTypeInfoOrErr) | |||
6455 | return ToArgumentTypeInfoOrErr.takeError(); | |||
6456 | ||||
6457 | return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( | |||
6458 | E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc, | |||
6459 | ToRParenLoc); | |||
6460 | } | |||
6461 | ||||
6462 | ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr()); | |||
6463 | if (!ToArgumentExprOrErr) | |||
6464 | return ToArgumentExprOrErr.takeError(); | |||
6465 | ||||
6466 | return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( | |||
6467 | E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc); | |||
6468 | } | |||
6469 | ||||
6470 | ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) { | |||
6471 | auto Imp = importSeq( | |||
6472 | E->getLHS(), E->getRHS(), E->getType(), E->getOperatorLoc()); | |||
6473 | if (!Imp) | |||
6474 | return Imp.takeError(); | |||
6475 | ||||
6476 | Expr *ToLHS, *ToRHS; | |||
6477 | QualType ToType; | |||
6478 | SourceLocation ToOperatorLoc; | |||
6479 | std::tie(ToLHS, ToRHS, ToType, ToOperatorLoc) = *Imp; | |||
6480 | ||||
6481 | return new (Importer.getToContext()) BinaryOperator( | |||
6482 | ToLHS, ToRHS, E->getOpcode(), ToType, E->getValueKind(), | |||
6483 | E->getObjectKind(), ToOperatorLoc, E->getFPFeatures()); | |||
6484 | } | |||
6485 | ||||
6486 | ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) { | |||
6487 | auto Imp = importSeq( | |||
6488 | E->getCond(), E->getQuestionLoc(), E->getLHS(), E->getColonLoc(), | |||
6489 | E->getRHS(), E->getType()); | |||
6490 | if (!Imp) | |||
6491 | return Imp.takeError(); | |||
6492 | ||||
6493 | Expr *ToCond, *ToLHS, *ToRHS; | |||
6494 | SourceLocation ToQuestionLoc, ToColonLoc; | |||
6495 | QualType ToType; | |||
6496 | std::tie(ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType) = *Imp; | |||
6497 | ||||
6498 | return new (Importer.getToContext()) ConditionalOperator( | |||
6499 | ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType, | |||
6500 | E->getValueKind(), E->getObjectKind()); | |||
6501 | } | |||
6502 | ||||
6503 | ExpectedStmt ASTNodeImporter::VisitBinaryConditionalOperator( | |||
6504 | BinaryConditionalOperator *E) { | |||
6505 | auto Imp = importSeq( | |||
6506 | E->getCommon(), E->getOpaqueValue(), E->getCond(), E->getTrueExpr(), | |||
6507 | E->getFalseExpr(), E->getQuestionLoc(), E->getColonLoc(), E->getType()); | |||
6508 | if (!Imp) | |||
6509 | return Imp.takeError(); | |||
6510 | ||||
6511 | Expr *ToCommon, *ToCond, *ToTrueExpr, *ToFalseExpr; | |||
6512 | OpaqueValueExpr *ToOpaqueValue; | |||
6513 | SourceLocation ToQuestionLoc, ToColonLoc; | |||
6514 | QualType ToType; | |||
6515 | std::tie( | |||
6516 | ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, ToQuestionLoc, | |||
6517 | ToColonLoc, ToType) = *Imp; | |||
6518 | ||||
6519 | return new (Importer.getToContext()) BinaryConditionalOperator( | |||
6520 | ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, | |||
6521 | ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(), | |||
6522 | E->getObjectKind()); | |||
6523 | } | |||
6524 | ||||
6525 | ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) { | |||
6526 | auto Imp = importSeq( | |||
6527 | E->getBeginLoc(), E->getQueriedTypeSourceInfo(), | |||
6528 | E->getDimensionExpression(), E->getEndLoc(), E->getType()); | |||
6529 | if (!Imp) | |||
6530 | return Imp.takeError(); | |||
6531 | ||||
6532 | SourceLocation ToBeginLoc, ToEndLoc; | |||
6533 | TypeSourceInfo *ToQueriedTypeSourceInfo; | |||
6534 | Expr *ToDimensionExpression; | |||
6535 | QualType ToType; | |||
6536 | std::tie( | |||
6537 | ToBeginLoc, ToQueriedTypeSourceInfo, ToDimensionExpression, ToEndLoc, | |||
6538 | ToType) = *Imp; | |||
6539 | ||||
6540 | return new (Importer.getToContext()) ArrayTypeTraitExpr( | |||
6541 | ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(), | |||
6542 | ToDimensionExpression, ToEndLoc, ToType); | |||
6543 | } | |||
6544 | ||||
6545 | ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) { | |||
6546 | auto Imp = importSeq( | |||
6547 | E->getBeginLoc(), E->getQueriedExpression(), E->getEndLoc(), E->getType()); | |||
6548 | if (!Imp) | |||
6549 | return Imp.takeError(); | |||
6550 | ||||
6551 | SourceLocation ToBeginLoc, ToEndLoc; | |||
6552 | Expr *ToQueriedExpression; | |||
6553 | QualType ToType; | |||
6554 | std::tie(ToBeginLoc, ToQueriedExpression, ToEndLoc, ToType) = *Imp; | |||
6555 | ||||
6556 | return new (Importer.getToContext()) ExpressionTraitExpr( | |||
6557 | ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(), | |||
6558 | ToEndLoc, ToType); | |||
6559 | } | |||
6560 | ||||
6561 | ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) { | |||
6562 | auto Imp = importSeq( | |||
6563 | E->getLocation(), E->getType(), E->getSourceExpr()); | |||
6564 | if (!Imp) | |||
6565 | return Imp.takeError(); | |||
6566 | ||||
6567 | SourceLocation ToLocation; | |||
6568 | QualType ToType; | |||
6569 | Expr *ToSourceExpr; | |||
6570 | std::tie(ToLocation, ToType, ToSourceExpr) = *Imp; | |||
6571 | ||||
6572 | return new (Importer.getToContext()) OpaqueValueExpr( | |||
6573 | ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr); | |||
6574 | } | |||
6575 | ||||
6576 | ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { | |||
6577 | auto Imp = importSeq( | |||
6578 | E->getLHS(), E->getRHS(), E->getType(), E->getRBracketLoc()); | |||
6579 | if (!Imp) | |||
6580 | return Imp.takeError(); | |||
6581 | ||||
6582 | Expr *ToLHS, *ToRHS; | |||
6583 | SourceLocation ToRBracketLoc; | |||
6584 | QualType ToType; | |||
6585 | std::tie(ToLHS, ToRHS, ToType, ToRBracketLoc) = *Imp; | |||
6586 | ||||
6587 | return new (Importer.getToContext()) ArraySubscriptExpr( | |||
6588 | ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(), | |||
6589 | ToRBracketLoc); | |||
6590 | } | |||
6591 | ||||
6592 | ExpectedStmt | |||
6593 | ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { | |||
6594 | auto Imp = importSeq( | |||
6595 | E->getLHS(), E->getRHS(), E->getType(), E->getComputationLHSType(), | |||
6596 | E->getComputationResultType(), E->getOperatorLoc()); | |||
6597 | if (!Imp) | |||
6598 | return Imp.takeError(); | |||
6599 | ||||
6600 | Expr *ToLHS, *ToRHS; | |||
6601 | QualType ToType, ToComputationLHSType, ToComputationResultType; | |||
6602 | SourceLocation ToOperatorLoc; | |||
6603 | std::tie(ToLHS, ToRHS, ToType, ToComputationLHSType, ToComputationResultType, | |||
6604 | ToOperatorLoc) = *Imp; | |||
6605 | ||||
6606 | return new (Importer.getToContext()) CompoundAssignOperator( | |||
6607 | ToLHS, ToRHS, E->getOpcode(), ToType, E->getValueKind(), | |||
6608 | E->getObjectKind(), ToComputationLHSType, ToComputationResultType, | |||
6609 | ToOperatorLoc, E->getFPFeatures()); | |||
6610 | } | |||
6611 | ||||
6612 | Expected<CXXCastPath> | |||
6613 | ASTNodeImporter::ImportCastPath(CastExpr *CE) { | |||
6614 | CXXCastPath Path; | |||
6615 | for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) { | |||
6616 | if (auto SpecOrErr = import(*I)) | |||
6617 | Path.push_back(*SpecOrErr); | |||
6618 | else | |||
6619 | return SpecOrErr.takeError(); | |||
6620 | } | |||
6621 | return Path; | |||
6622 | } | |||
6623 | ||||
6624 | ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
6625 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
6626 | if (!ToTypeOrErr) | |||
6627 | return ToTypeOrErr.takeError(); | |||
6628 | ||||
6629 | ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); | |||
6630 | if (!ToSubExprOrErr) | |||
6631 | return ToSubExprOrErr.takeError(); | |||
6632 | ||||
6633 | Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); | |||
6634 | if (!ToBasePathOrErr) | |||
6635 | return ToBasePathOrErr.takeError(); | |||
6636 | ||||
6637 | return ImplicitCastExpr::Create( | |||
6638 | Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr, | |||
6639 | &(*ToBasePathOrErr), E->getValueKind()); | |||
6640 | } | |||
6641 | ||||
6642 | ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) { | |||
6643 | auto Imp1 = importSeq( | |||
6644 | E->getType(), E->getSubExpr(), E->getTypeInfoAsWritten()); | |||
6645 | if (!Imp1) | |||
6646 | return Imp1.takeError(); | |||
6647 | ||||
6648 | QualType ToType; | |||
6649 | Expr *ToSubExpr; | |||
6650 | TypeSourceInfo *ToTypeInfoAsWritten; | |||
6651 | std::tie(ToType, ToSubExpr, ToTypeInfoAsWritten) = *Imp1; | |||
6652 | ||||
6653 | Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); | |||
6654 | if (!ToBasePathOrErr) | |||
6655 | return ToBasePathOrErr.takeError(); | |||
6656 | CXXCastPath *ToBasePath = &(*ToBasePathOrErr); | |||
6657 | ||||
6658 | switch (E->getStmtClass()) { | |||
6659 | case Stmt::CStyleCastExprClass: { | |||
6660 | auto *CCE = cast<CStyleCastExpr>(E); | |||
6661 | ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc()); | |||
6662 | if (!ToLParenLocOrErr) | |||
6663 | return ToLParenLocOrErr.takeError(); | |||
6664 | ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc()); | |||
6665 | if (!ToRParenLocOrErr) | |||
6666 | return ToRParenLocOrErr.takeError(); | |||
6667 | return CStyleCastExpr::Create( | |||
6668 | Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(), | |||
6669 | ToSubExpr, ToBasePath, ToTypeInfoAsWritten, *ToLParenLocOrErr, | |||
6670 | *ToRParenLocOrErr); | |||
6671 | } | |||
6672 | ||||
6673 | case Stmt::CXXFunctionalCastExprClass: { | |||
6674 | auto *FCE = cast<CXXFunctionalCastExpr>(E); | |||
6675 | ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc()); | |||
6676 | if (!ToLParenLocOrErr) | |||
6677 | return ToLParenLocOrErr.takeError(); | |||
6678 | ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc()); | |||
6679 | if (!ToRParenLocOrErr) | |||
6680 | return ToRParenLocOrErr.takeError(); | |||
6681 | return CXXFunctionalCastExpr::Create( | |||
6682 | Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten, | |||
6683 | E->getCastKind(), ToSubExpr, ToBasePath, *ToLParenLocOrErr, | |||
6684 | *ToRParenLocOrErr); | |||
6685 | } | |||
6686 | ||||
6687 | case Stmt::ObjCBridgedCastExprClass: { | |||
6688 | auto *OCE = cast<ObjCBridgedCastExpr>(E); | |||
6689 | ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc()); | |||
6690 | if (!ToLParenLocOrErr) | |||
6691 | return ToLParenLocOrErr.takeError(); | |||
6692 | ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc()); | |||
6693 | if (!ToBridgeKeywordLocOrErr) | |||
6694 | return ToBridgeKeywordLocOrErr.takeError(); | |||
6695 | return new (Importer.getToContext()) ObjCBridgedCastExpr( | |||
6696 | *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(), | |||
6697 | *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr); | |||
6698 | } | |||
6699 | default: | |||
6700 | llvm_unreachable("Cast expression of unsupported type!")::llvm::llvm_unreachable_internal("Cast expression of unsupported type!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 6700); | |||
6701 | return make_error<ImportError>(ImportError::UnsupportedConstruct); | |||
6702 | } | |||
6703 | } | |||
6704 | ||||
6705 | ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) { | |||
6706 | SmallVector<OffsetOfNode, 4> ToNodes; | |||
6707 | for (int I = 0, N = E->getNumComponents(); I < N; ++I) { | |||
6708 | const OffsetOfNode &FromNode = E->getComponent(I); | |||
6709 | ||||
6710 | SourceLocation ToBeginLoc, ToEndLoc; | |||
6711 | if (FromNode.getKind() != OffsetOfNode::Base) { | |||
6712 | auto Imp = importSeq(FromNode.getBeginLoc(), FromNode.getEndLoc()); | |||
6713 | if (!Imp) | |||
6714 | return Imp.takeError(); | |||
6715 | std::tie(ToBeginLoc, ToEndLoc) = *Imp; | |||
6716 | } | |||
6717 | ||||
6718 | switch (FromNode.getKind()) { | |||
6719 | case OffsetOfNode::Array: | |||
6720 | ToNodes.push_back( | |||
6721 | OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc)); | |||
6722 | break; | |||
6723 | case OffsetOfNode::Base: { | |||
6724 | auto ToBSOrErr = import(FromNode.getBase()); | |||
6725 | if (!ToBSOrErr) | |||
6726 | return ToBSOrErr.takeError(); | |||
6727 | ToNodes.push_back(OffsetOfNode(*ToBSOrErr)); | |||
6728 | break; | |||
6729 | } | |||
6730 | case OffsetOfNode::Field: { | |||
6731 | auto ToFieldOrErr = import(FromNode.getField()); | |||
6732 | if (!ToFieldOrErr) | |||
6733 | return ToFieldOrErr.takeError(); | |||
6734 | ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc)); | |||
6735 | break; | |||
6736 | } | |||
6737 | case OffsetOfNode::Identifier: { | |||
6738 | IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName()); | |||
6739 | ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc)); | |||
6740 | break; | |||
6741 | } | |||
6742 | } | |||
6743 | } | |||
6744 | ||||
6745 | SmallVector<Expr *, 4> ToExprs(E->getNumExpressions()); | |||
6746 | for (int I = 0, N = E->getNumExpressions(); I < N; ++I) { | |||
6747 | ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I)); | |||
6748 | if (!ToIndexExprOrErr) | |||
6749 | return ToIndexExprOrErr.takeError(); | |||
6750 | ToExprs[I] = *ToIndexExprOrErr; | |||
6751 | } | |||
6752 | ||||
6753 | auto Imp = importSeq( | |||
6754 | E->getType(), E->getTypeSourceInfo(), E->getOperatorLoc(), | |||
6755 | E->getRParenLoc()); | |||
6756 | if (!Imp) | |||
6757 | return Imp.takeError(); | |||
6758 | ||||
6759 | QualType ToType; | |||
6760 | TypeSourceInfo *ToTypeSourceInfo; | |||
6761 | SourceLocation ToOperatorLoc, ToRParenLoc; | |||
6762 | std::tie(ToType, ToTypeSourceInfo, ToOperatorLoc, ToRParenLoc) = *Imp; | |||
6763 | ||||
6764 | return OffsetOfExpr::Create( | |||
6765 | Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes, | |||
6766 | ToExprs, ToRParenLoc); | |||
6767 | } | |||
6768 | ||||
6769 | ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) { | |||
6770 | auto Imp = importSeq( | |||
6771 | E->getType(), E->getOperand(), E->getBeginLoc(), E->getEndLoc()); | |||
6772 | if (!Imp) | |||
6773 | return Imp.takeError(); | |||
6774 | ||||
6775 | QualType ToType; | |||
6776 | Expr *ToOperand; | |||
6777 | SourceLocation ToBeginLoc, ToEndLoc; | |||
6778 | std::tie(ToType, ToOperand, ToBeginLoc, ToEndLoc) = *Imp; | |||
6779 | ||||
6780 | CanThrowResult ToCanThrow; | |||
6781 | if (E->isValueDependent()) | |||
6782 | ToCanThrow = CT_Dependent; | |||
6783 | else | |||
6784 | ToCanThrow = E->getValue() ? CT_Can : CT_Cannot; | |||
6785 | ||||
6786 | return new (Importer.getToContext()) CXXNoexceptExpr( | |||
6787 | ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc); | |||
6788 | } | |||
6789 | ||||
6790 | ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) { | |||
6791 | auto Imp = importSeq(E->getSubExpr(), E->getType(), E->getThrowLoc()); | |||
6792 | if (!Imp) | |||
6793 | return Imp.takeError(); | |||
6794 | ||||
6795 | Expr *ToSubExpr; | |||
6796 | QualType ToType; | |||
6797 | SourceLocation ToThrowLoc; | |||
6798 | std::tie(ToSubExpr, ToType, ToThrowLoc) = *Imp; | |||
6799 | ||||
6800 | return new (Importer.getToContext()) CXXThrowExpr( | |||
6801 | ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope()); | |||
6802 | } | |||
6803 | ||||
6804 | ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { | |||
6805 | ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation()); | |||
6806 | if (!ToUsedLocOrErr) | |||
6807 | return ToUsedLocOrErr.takeError(); | |||
6808 | ||||
6809 | auto ToParamOrErr = import(E->getParam()); | |||
6810 | if (!ToParamOrErr) | |||
6811 | return ToParamOrErr.takeError(); | |||
6812 | ||||
6813 | auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); | |||
6814 | if (!UsedContextOrErr) | |||
6815 | return UsedContextOrErr.takeError(); | |||
6816 | ||||
6817 | return CXXDefaultArgExpr::Create( | |||
6818 | Importer.getToContext(), *ToUsedLocOrErr, *ToParamOrErr, *UsedContextOrErr); | |||
6819 | } | |||
6820 | ||||
6821 | ExpectedStmt | |||
6822 | ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { | |||
6823 | auto Imp = importSeq( | |||
6824 | E->getType(), E->getTypeSourceInfo(), E->getRParenLoc()); | |||
6825 | if (!Imp) | |||
6826 | return Imp.takeError(); | |||
6827 | ||||
6828 | QualType ToType; | |||
6829 | TypeSourceInfo *ToTypeSourceInfo; | |||
6830 | SourceLocation ToRParenLoc; | |||
6831 | std::tie(ToType, ToTypeSourceInfo, ToRParenLoc) = *Imp; | |||
6832 | ||||
6833 | return new (Importer.getToContext()) CXXScalarValueInitExpr( | |||
6834 | ToType, ToTypeSourceInfo, ToRParenLoc); | |||
6835 | } | |||
6836 | ||||
6837 | ExpectedStmt | |||
6838 | ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { | |||
6839 | ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); | |||
6840 | if (!ToSubExprOrErr) | |||
6841 | return ToSubExprOrErr.takeError(); | |||
6842 | ||||
6843 | auto ToDtorOrErr = import(E->getTemporary()->getDestructor()); | |||
6844 | if (!ToDtorOrErr) | |||
6845 | return ToDtorOrErr.takeError(); | |||
6846 | ||||
6847 | ASTContext &ToCtx = Importer.getToContext(); | |||
6848 | CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr); | |||
6849 | return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr); | |||
6850 | } | |||
6851 | ||||
6852 | ExpectedStmt | |||
6853 | ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { | |||
6854 | auto Imp = importSeq( | |||
6855 | E->getConstructor(), E->getType(), E->getTypeSourceInfo(), | |||
6856 | E->getParenOrBraceRange()); | |||
6857 | if (!Imp) | |||
6858 | return Imp.takeError(); | |||
6859 | ||||
6860 | CXXConstructorDecl *ToConstructor; | |||
6861 | QualType ToType; | |||
6862 | TypeSourceInfo *ToTypeSourceInfo; | |||
6863 | SourceRange ToParenOrBraceRange; | |||
6864 | std::tie(ToConstructor, ToType, ToTypeSourceInfo, ToParenOrBraceRange) = *Imp; | |||
6865 | ||||
6866 | SmallVector<Expr *, 8> ToArgs(E->getNumArgs()); | |||
6867 | if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) | |||
6868 | return std::move(Err); | |||
6869 | ||||
6870 | return CXXTemporaryObjectExpr::Create( | |||
6871 | Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs, | |||
6872 | ToParenOrBraceRange, E->hadMultipleCandidates(), | |||
6873 | E->isListInitialization(), E->isStdInitListInitialization(), | |||
6874 | E->requiresZeroInitialization()); | |||
6875 | } | |||
6876 | ||||
6877 | ExpectedStmt | |||
6878 | ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) { | |||
6879 | auto Imp = importSeq( | |||
6880 | E->getType(), E->GetTemporaryExpr(), E->getExtendingDecl()); | |||
6881 | if (!Imp) | |||
6882 | return Imp.takeError(); | |||
6883 | ||||
6884 | QualType ToType; | |||
6885 | Expr *ToTemporaryExpr; | |||
6886 | const ValueDecl *ToExtendingDecl; | |||
6887 | std::tie(ToType, ToTemporaryExpr, ToExtendingDecl) = *Imp; | |||
6888 | ||||
6889 | auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr( | |||
6890 | ToType, ToTemporaryExpr, E->isBoundToLvalueReference()); | |||
6891 | ||||
6892 | // FIXME: Should ManglingNumber get numbers associated with 'to' context? | |||
6893 | ToMTE->setExtendingDecl(ToExtendingDecl, E->getManglingNumber()); | |||
6894 | return ToMTE; | |||
6895 | } | |||
6896 | ||||
6897 | ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) { | |||
6898 | auto Imp = importSeq( | |||
6899 | E->getType(), E->getPattern(), E->getEllipsisLoc()); | |||
6900 | if (!Imp) | |||
6901 | return Imp.takeError(); | |||
6902 | ||||
6903 | QualType ToType; | |||
6904 | Expr *ToPattern; | |||
6905 | SourceLocation ToEllipsisLoc; | |||
6906 | std::tie(ToType, ToPattern, ToEllipsisLoc) = *Imp; | |||
6907 | ||||
6908 | return new (Importer.getToContext()) PackExpansionExpr( | |||
6909 | ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions()); | |||
6910 | } | |||
6911 | ||||
6912 | ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { | |||
6913 | auto Imp = importSeq( | |||
6914 | E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc()); | |||
6915 | if (!Imp) | |||
6916 | return Imp.takeError(); | |||
6917 | ||||
6918 | SourceLocation ToOperatorLoc, ToPackLoc, ToRParenLoc; | |||
6919 | NamedDecl *ToPack; | |||
6920 | std::tie(ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc) = *Imp; | |||
6921 | ||||
6922 | Optional<unsigned> Length; | |||
6923 | if (!E->isValueDependent()) | |||
6924 | Length = E->getPackLength(); | |||
6925 | ||||
6926 | SmallVector<TemplateArgument, 8> ToPartialArguments; | |||
6927 | if (E->isPartiallySubstituted()) { | |||
6928 | if (Error Err = ImportTemplateArguments( | |||
6929 | E->getPartialArguments().data(), | |||
6930 | E->getPartialArguments().size(), | |||
6931 | ToPartialArguments)) | |||
6932 | return std::move(Err); | |||
6933 | } | |||
6934 | ||||
6935 | return SizeOfPackExpr::Create( | |||
6936 | Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc, | |||
6937 | Length, ToPartialArguments); | |||
6938 | } | |||
6939 | ||||
6940 | ||||
6941 | ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) { | |||
6942 | auto Imp = importSeq( | |||
6943 | E->getOperatorNew(), E->getOperatorDelete(), E->getTypeIdParens(), | |||
6944 | E->getArraySize(), E->getInitializer(), E->getType(), | |||
6945 | E->getAllocatedTypeSourceInfo(), E->getSourceRange(), | |||
6946 | E->getDirectInitRange()); | |||
6947 | if (!Imp) | |||
6948 | return Imp.takeError(); | |||
6949 | ||||
6950 | FunctionDecl *ToOperatorNew, *ToOperatorDelete; | |||
6951 | SourceRange ToTypeIdParens, ToSourceRange, ToDirectInitRange; | |||
6952 | Optional<Expr *> ToArraySize; | |||
6953 | Expr *ToInitializer; | |||
6954 | QualType ToType; | |||
6955 | TypeSourceInfo *ToAllocatedTypeSourceInfo; | |||
6956 | std::tie( | |||
6957 | ToOperatorNew, ToOperatorDelete, ToTypeIdParens, ToArraySize, ToInitializer, | |||
6958 | ToType, ToAllocatedTypeSourceInfo, ToSourceRange, ToDirectInitRange) = *Imp; | |||
6959 | ||||
6960 | SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs()); | |||
6961 | if (Error Err = | |||
6962 | ImportContainerChecked(E->placement_arguments(), ToPlacementArgs)) | |||
6963 | return std::move(Err); | |||
6964 | ||||
6965 | return CXXNewExpr::Create( | |||
6966 | Importer.getToContext(), E->isGlobalNew(), ToOperatorNew, | |||
6967 | ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(), | |||
6968 | ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(), | |||
6969 | ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange, | |||
6970 | ToDirectInitRange); | |||
6971 | } | |||
6972 | ||||
6973 | ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) { | |||
6974 | auto Imp = importSeq( | |||
6975 | E->getType(), E->getOperatorDelete(), E->getArgument(), E->getBeginLoc()); | |||
6976 | if (!Imp) | |||
6977 | return Imp.takeError(); | |||
6978 | ||||
6979 | QualType ToType; | |||
6980 | FunctionDecl *ToOperatorDelete; | |||
6981 | Expr *ToArgument; | |||
6982 | SourceLocation ToBeginLoc; | |||
6983 | std::tie(ToType, ToOperatorDelete, ToArgument, ToBeginLoc) = *Imp; | |||
6984 | ||||
6985 | return new (Importer.getToContext()) CXXDeleteExpr( | |||
6986 | ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(), | |||
6987 | E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument, | |||
6988 | ToBeginLoc); | |||
6989 | } | |||
6990 | ||||
6991 | ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
6992 | auto Imp = importSeq( | |||
6993 | E->getType(), E->getLocation(), E->getConstructor(), | |||
6994 | E->getParenOrBraceRange()); | |||
6995 | if (!Imp) | |||
6996 | return Imp.takeError(); | |||
6997 | ||||
6998 | QualType ToType; | |||
6999 | SourceLocation ToLocation; | |||
7000 | CXXConstructorDecl *ToConstructor; | |||
7001 | SourceRange ToParenOrBraceRange; | |||
7002 | std::tie(ToType, ToLocation, ToConstructor, ToParenOrBraceRange) = *Imp; | |||
7003 | ||||
7004 | SmallVector<Expr *, 6> ToArgs(E->getNumArgs()); | |||
7005 | if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) | |||
7006 | return std::move(Err); | |||
7007 | ||||
7008 | return CXXConstructExpr::Create( | |||
7009 | Importer.getToContext(), ToType, ToLocation, ToConstructor, | |||
7010 | E->isElidable(), ToArgs, E->hadMultipleCandidates(), | |||
7011 | E->isListInitialization(), E->isStdInitListInitialization(), | |||
7012 | E->requiresZeroInitialization(), E->getConstructionKind(), | |||
7013 | ToParenOrBraceRange); | |||
7014 | } | |||
7015 | ||||
7016 | ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) { | |||
7017 | ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); | |||
7018 | if (!ToSubExprOrErr) | |||
7019 | return ToSubExprOrErr.takeError(); | |||
7020 | ||||
7021 | SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects()); | |||
7022 | if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects)) | |||
7023 | return std::move(Err); | |||
7024 | ||||
7025 | return ExprWithCleanups::Create( | |||
7026 | Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(), | |||
7027 | ToObjects); | |||
7028 | } | |||
7029 | ||||
7030 | ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { | |||
7031 | auto Imp = importSeq( | |||
7032 | E->getCallee(), E->getType(), E->getRParenLoc()); | |||
7033 | if (!Imp) | |||
7034 | return Imp.takeError(); | |||
7035 | ||||
7036 | Expr *ToCallee; | |||
7037 | QualType ToType; | |||
7038 | SourceLocation ToRParenLoc; | |||
7039 | std::tie(ToCallee, ToType, ToRParenLoc) = *Imp; | |||
7040 | ||||
7041 | SmallVector<Expr *, 4> ToArgs(E->getNumArgs()); | |||
7042 | if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) | |||
7043 | return std::move(Err); | |||
7044 | ||||
7045 | return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, | |||
7046 | ToType, E->getValueKind(), ToRParenLoc); | |||
7047 | } | |||
7048 | ||||
7049 | ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) { | |||
7050 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
7051 | if (!ToTypeOrErr) | |||
7052 | return ToTypeOrErr.takeError(); | |||
7053 | ||||
7054 | ExpectedSLoc ToLocationOrErr = import(E->getLocation()); | |||
7055 | if (!ToLocationOrErr) | |||
7056 | return ToLocationOrErr.takeError(); | |||
7057 | ||||
7058 | return new (Importer.getToContext()) CXXThisExpr( | |||
7059 | *ToLocationOrErr, *ToTypeOrErr, E->isImplicit()); | |||
7060 | } | |||
7061 | ||||
7062 | ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { | |||
7063 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
7064 | if (!ToTypeOrErr) | |||
7065 | return ToTypeOrErr.takeError(); | |||
7066 | ||||
7067 | ExpectedSLoc ToLocationOrErr = import(E->getLocation()); | |||
7068 | if (!ToLocationOrErr) | |||
7069 | return ToLocationOrErr.takeError(); | |||
7070 | ||||
7071 | return new (Importer.getToContext()) CXXBoolLiteralExpr( | |||
7072 | E->getValue(), *ToTypeOrErr, *ToLocationOrErr); | |||
7073 | } | |||
7074 | ||||
7075 | ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) { | |||
7076 | auto Imp1 = importSeq( | |||
7077 | E->getBase(), E->getOperatorLoc(), E->getQualifierLoc(), | |||
7078 | E->getTemplateKeywordLoc(), E->getMemberDecl(), E->getType()); | |||
7079 | if (!Imp1) | |||
7080 | return Imp1.takeError(); | |||
7081 | ||||
7082 | Expr *ToBase; | |||
7083 | SourceLocation ToOperatorLoc, ToTemplateKeywordLoc; | |||
7084 | NestedNameSpecifierLoc ToQualifierLoc; | |||
7085 | ValueDecl *ToMemberDecl; | |||
7086 | QualType ToType; | |||
7087 | std::tie( | |||
7088 | ToBase, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, ToMemberDecl, | |||
7089 | ToType) = *Imp1; | |||
7090 | ||||
7091 | auto Imp2 = importSeq( | |||
7092 | E->getFoundDecl().getDecl(), E->getMemberNameInfo().getName(), | |||
7093 | E->getMemberNameInfo().getLoc(), E->getLAngleLoc(), E->getRAngleLoc()); | |||
7094 | if (!Imp2) | |||
7095 | return Imp2.takeError(); | |||
7096 | NamedDecl *ToDecl; | |||
7097 | DeclarationName ToName; | |||
7098 | SourceLocation ToLoc, ToLAngleLoc, ToRAngleLoc; | |||
7099 | std::tie(ToDecl, ToName, ToLoc, ToLAngleLoc, ToRAngleLoc) = *Imp2; | |||
7100 | ||||
7101 | DeclAccessPair ToFoundDecl = | |||
7102 | DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess()); | |||
7103 | ||||
7104 | DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc); | |||
7105 | ||||
7106 | TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; | |||
7107 | if (E->hasExplicitTemplateArgs()) { | |||
7108 | if (Error Err = | |||
7109 | ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), | |||
7110 | E->template_arguments(), ToTAInfo)) | |||
7111 | return std::move(Err); | |||
7112 | ResInfo = &ToTAInfo; | |||
7113 | } | |||
7114 | ||||
7115 | return MemberExpr::Create( | |||
7116 | Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc, | |||
7117 | ToQualifierLoc, ToTemplateKeywordLoc, ToMemberDecl, ToFoundDecl, | |||
7118 | ToMemberNameInfo, ResInfo, ToType, E->getValueKind(), E->getObjectKind()); | |||
7119 | } | |||
7120 | ||||
7121 | ExpectedStmt | |||
7122 | ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { | |||
7123 | auto Imp = importSeq( | |||
7124 | E->getBase(), E->getOperatorLoc(), E->getQualifierLoc(), | |||
7125 | E->getScopeTypeInfo(), E->getColonColonLoc(), E->getTildeLoc()); | |||
7126 | if (!Imp) | |||
7127 | return Imp.takeError(); | |||
7128 | ||||
7129 | Expr *ToBase; | |||
7130 | SourceLocation ToOperatorLoc, ToColonColonLoc, ToTildeLoc; | |||
7131 | NestedNameSpecifierLoc ToQualifierLoc; | |||
7132 | TypeSourceInfo *ToScopeTypeInfo; | |||
7133 | std::tie( | |||
7134 | ToBase, ToOperatorLoc, ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, | |||
7135 | ToTildeLoc) = *Imp; | |||
7136 | ||||
7137 | PseudoDestructorTypeStorage Storage; | |||
7138 | if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) { | |||
7139 | IdentifierInfo *ToII = Importer.Import(FromII); | |||
7140 | ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc()); | |||
7141 | if (!ToDestroyedTypeLocOrErr) | |||
7142 | return ToDestroyedTypeLocOrErr.takeError(); | |||
7143 | Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr); | |||
7144 | } else { | |||
7145 | if (auto ToTIOrErr = import(E->getDestroyedTypeInfo())) | |||
7146 | Storage = PseudoDestructorTypeStorage(*ToTIOrErr); | |||
7147 | else | |||
7148 | return ToTIOrErr.takeError(); | |||
7149 | } | |||
7150 | ||||
7151 | return new (Importer.getToContext()) CXXPseudoDestructorExpr( | |||
7152 | Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc, | |||
7153 | ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage); | |||
7154 | } | |||
7155 | ||||
7156 | ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr( | |||
7157 | CXXDependentScopeMemberExpr *E) { | |||
7158 | auto Imp = importSeq( | |||
7159 | E->getType(), E->getOperatorLoc(), E->getQualifierLoc(), | |||
7160 | E->getTemplateKeywordLoc(), E->getFirstQualifierFoundInScope()); | |||
7161 | if (!Imp) | |||
7162 | return Imp.takeError(); | |||
7163 | ||||
7164 | QualType ToType; | |||
7165 | SourceLocation ToOperatorLoc, ToTemplateKeywordLoc; | |||
7166 | NestedNameSpecifierLoc ToQualifierLoc; | |||
7167 | NamedDecl *ToFirstQualifierFoundInScope; | |||
7168 | std::tie( | |||
7169 | ToType, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, | |||
7170 | ToFirstQualifierFoundInScope) = *Imp; | |||
7171 | ||||
7172 | Expr *ToBase = nullptr; | |||
7173 | if (!E->isImplicitAccess()) { | |||
7174 | if (ExpectedExpr ToBaseOrErr = import(E->getBase())) | |||
7175 | ToBase = *ToBaseOrErr; | |||
7176 | else | |||
7177 | return ToBaseOrErr.takeError(); | |||
7178 | } | |||
7179 | ||||
7180 | TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; | |||
7181 | if (E->hasExplicitTemplateArgs()) { | |||
7182 | if (Error Err = ImportTemplateArgumentListInfo( | |||
7183 | E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(), | |||
7184 | ToTAInfo)) | |||
7185 | return std::move(Err); | |||
7186 | ResInfo = &ToTAInfo; | |||
7187 | } | |||
7188 | ||||
7189 | auto ToMemberNameInfoOrErr = importSeq(E->getMember(), E->getMemberLoc()); | |||
7190 | if (!ToMemberNameInfoOrErr) | |||
7191 | return ToMemberNameInfoOrErr.takeError(); | |||
7192 | DeclarationNameInfo ToMemberNameInfo( | |||
7193 | std::get<0>(*ToMemberNameInfoOrErr), std::get<1>(*ToMemberNameInfoOrErr)); | |||
7194 | // Import additional name location/type info. | |||
7195 | if (Error Err = ImportDeclarationNameLoc( | |||
7196 | E->getMemberNameInfo(), ToMemberNameInfo)) | |||
7197 | return std::move(Err); | |||
7198 | ||||
7199 | return CXXDependentScopeMemberExpr::Create( | |||
7200 | Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc, | |||
7201 | ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope, | |||
7202 | ToMemberNameInfo, ResInfo); | |||
7203 | } | |||
7204 | ||||
7205 | ExpectedStmt | |||
7206 | ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { | |||
7207 | auto Imp = importSeq( | |||
7208 | E->getQualifierLoc(), E->getTemplateKeywordLoc(), E->getDeclName(), | |||
7209 | E->getExprLoc(), E->getLAngleLoc(), E->getRAngleLoc()); | |||
7210 | if (!Imp) | |||
7211 | return Imp.takeError(); | |||
7212 | ||||
7213 | NestedNameSpecifierLoc ToQualifierLoc; | |||
7214 | SourceLocation ToTemplateKeywordLoc, ToExprLoc, ToLAngleLoc, ToRAngleLoc; | |||
7215 | DeclarationName ToDeclName; | |||
7216 | std::tie( | |||
7217 | ToQualifierLoc, ToTemplateKeywordLoc, ToDeclName, ToExprLoc, | |||
7218 | ToLAngleLoc, ToRAngleLoc) = *Imp; | |||
7219 | ||||
7220 | DeclarationNameInfo ToNameInfo(ToDeclName, ToExprLoc); | |||
7221 | if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) | |||
7222 | return std::move(Err); | |||
7223 | ||||
7224 | TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc); | |||
7225 | TemplateArgumentListInfo *ResInfo = nullptr; | |||
7226 | if (E->hasExplicitTemplateArgs()) { | |||
7227 | if (Error Err = | |||
7228 | ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) | |||
7229 | return std::move(Err); | |||
7230 | ResInfo = &ToTAInfo; | |||
7231 | } | |||
7232 | ||||
7233 | return DependentScopeDeclRefExpr::Create( | |||
7234 | Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, | |||
7235 | ToNameInfo, ResInfo); | |||
7236 | } | |||
7237 | ||||
7238 | ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr( | |||
7239 | CXXUnresolvedConstructExpr *E) { | |||
7240 | auto Imp = importSeq( | |||
7241 | E->getLParenLoc(), E->getRParenLoc(), E->getTypeSourceInfo()); | |||
7242 | if (!Imp) | |||
7243 | return Imp.takeError(); | |||
7244 | ||||
7245 | SourceLocation ToLParenLoc, ToRParenLoc; | |||
7246 | TypeSourceInfo *ToTypeSourceInfo; | |||
7247 | std::tie(ToLParenLoc, ToRParenLoc, ToTypeSourceInfo) = *Imp; | |||
7248 | ||||
7249 | SmallVector<Expr *, 8> ToArgs(E->arg_size()); | |||
7250 | if (Error Err = | |||
7251 | ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin())) | |||
7252 | return std::move(Err); | |||
7253 | ||||
7254 | return CXXUnresolvedConstructExpr::Create( | |||
7255 | Importer.getToContext(), ToTypeSourceInfo, ToLParenLoc, | |||
7256 | llvm::makeArrayRef(ToArgs), ToRParenLoc); | |||
7257 | } | |||
7258 | ||||
7259 | ExpectedStmt | |||
7260 | ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) { | |||
7261 | Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass()); | |||
7262 | if (!ToNamingClassOrErr) | |||
7263 | return ToNamingClassOrErr.takeError(); | |||
7264 | ||||
7265 | auto ToQualifierLocOrErr = import(E->getQualifierLoc()); | |||
7266 | if (!ToQualifierLocOrErr) | |||
7267 | return ToQualifierLocOrErr.takeError(); | |||
7268 | ||||
7269 | auto ToNameInfoOrErr = importSeq(E->getName(), E->getNameLoc()); | |||
7270 | if (!ToNameInfoOrErr) | |||
7271 | return ToNameInfoOrErr.takeError(); | |||
7272 | DeclarationNameInfo ToNameInfo( | |||
7273 | std::get<0>(*ToNameInfoOrErr), std::get<1>(*ToNameInfoOrErr)); | |||
7274 | // Import additional name location/type info. | |||
7275 | if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) | |||
7276 | return std::move(Err); | |||
7277 | ||||
7278 | UnresolvedSet<8> ToDecls; | |||
7279 | for (auto *D : E->decls()) | |||
7280 | if (auto ToDOrErr = import(D)) | |||
7281 | ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); | |||
7282 | else | |||
7283 | return ToDOrErr.takeError(); | |||
7284 | ||||
7285 | if (E->hasExplicitTemplateArgs() && E->getTemplateKeywordLoc().isValid()) { | |||
7286 | TemplateArgumentListInfo ToTAInfo; | |||
7287 | if (Error Err = ImportTemplateArgumentListInfo( | |||
7288 | E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(), | |||
7289 | ToTAInfo)) | |||
7290 | return std::move(Err); | |||
7291 | ||||
7292 | ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc()); | |||
7293 | if (!ToTemplateKeywordLocOrErr) | |||
7294 | return ToTemplateKeywordLocOrErr.takeError(); | |||
7295 | ||||
7296 | return UnresolvedLookupExpr::Create( | |||
7297 | Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, | |||
7298 | *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo, | |||
7299 | ToDecls.begin(), ToDecls.end()); | |||
7300 | } | |||
7301 | ||||
7302 | return UnresolvedLookupExpr::Create( | |||
7303 | Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, | |||
7304 | ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(), | |||
7305 | ToDecls.end()); | |||
7306 | } | |||
7307 | ||||
7308 | ExpectedStmt | |||
7309 | ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) { | |||
7310 | auto Imp1 = importSeq( | |||
7311 | E->getType(), E->getOperatorLoc(), E->getQualifierLoc(), | |||
7312 | E->getTemplateKeywordLoc()); | |||
7313 | if (!Imp1) | |||
7314 | return Imp1.takeError(); | |||
7315 | ||||
7316 | QualType ToType; | |||
7317 | SourceLocation ToOperatorLoc, ToTemplateKeywordLoc; | |||
7318 | NestedNameSpecifierLoc ToQualifierLoc; | |||
7319 | std::tie(ToType, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc) = *Imp1; | |||
7320 | ||||
7321 | auto Imp2 = importSeq(E->getName(), E->getNameLoc()); | |||
7322 | if (!Imp2) | |||
7323 | return Imp2.takeError(); | |||
7324 | DeclarationNameInfo ToNameInfo(std::get<0>(*Imp2), std::get<1>(*Imp2)); | |||
7325 | // Import additional name location/type info. | |||
7326 | if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) | |||
7327 | return std::move(Err); | |||
7328 | ||||
7329 | UnresolvedSet<8> ToDecls; | |||
7330 | for (Decl *D : E->decls()) | |||
7331 | if (auto ToDOrErr = import(D)) | |||
7332 | ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); | |||
7333 | else | |||
7334 | return ToDOrErr.takeError(); | |||
7335 | ||||
7336 | TemplateArgumentListInfo ToTAInfo; | |||
7337 | TemplateArgumentListInfo *ResInfo = nullptr; | |||
7338 | if (E->hasExplicitTemplateArgs()) { | |||
7339 | if (Error Err = | |||
7340 | ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) | |||
7341 | return std::move(Err); | |||
7342 | ResInfo = &ToTAInfo; | |||
7343 | } | |||
7344 | ||||
7345 | Expr *ToBase = nullptr; | |||
7346 | if (!E->isImplicitAccess()) { | |||
7347 | if (ExpectedExpr ToBaseOrErr = import(E->getBase())) | |||
7348 | ToBase = *ToBaseOrErr; | |||
7349 | else | |||
7350 | return ToBaseOrErr.takeError(); | |||
7351 | } | |||
7352 | ||||
7353 | return UnresolvedMemberExpr::Create( | |||
7354 | Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType, | |||
7355 | E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, | |||
7356 | ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end()); | |||
7357 | } | |||
7358 | ||||
7359 | ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) { | |||
7360 | auto Imp = importSeq(E->getCallee(), E->getType(), E->getRParenLoc()); | |||
7361 | if (!Imp) | |||
7362 | return Imp.takeError(); | |||
7363 | ||||
7364 | Expr *ToCallee; | |||
7365 | QualType ToType; | |||
7366 | SourceLocation ToRParenLoc; | |||
7367 | std::tie(ToCallee, ToType, ToRParenLoc) = *Imp; | |||
7368 | ||||
7369 | unsigned NumArgs = E->getNumArgs(); | |||
7370 | llvm::SmallVector<Expr *, 2> ToArgs(NumArgs); | |||
7371 | if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) | |||
7372 | return std::move(Err); | |||
7373 | ||||
7374 | if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { | |||
7375 | return CXXOperatorCallExpr::Create( | |||
7376 | Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType, | |||
7377 | OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(), | |||
7378 | OCE->getADLCallKind()); | |||
7379 | } | |||
7380 | ||||
7381 | return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType, | |||
7382 | E->getValueKind(), ToRParenLoc, /*MinNumArgs=*/0, | |||
7383 | E->getADLCallKind()); | |||
7384 | } | |||
7385 | ||||
7386 | ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) { | |||
7387 | CXXRecordDecl *FromClass = E->getLambdaClass(); | |||
7388 | auto ToClassOrErr = import(FromClass); | |||
7389 | if (!ToClassOrErr) | |||
7390 | return ToClassOrErr.takeError(); | |||
7391 | CXXRecordDecl *ToClass = *ToClassOrErr; | |||
7392 | ||||
7393 | // NOTE: lambda classes are created with BeingDefined flag set up. | |||
7394 | // It means that ImportDefinition doesn't work for them and we should fill it | |||
7395 | // manually. | |||
7396 | if (ToClass->isBeingDefined()) | |||
7397 | if (Error Err = ImportDeclContext(FromClass, /*ForceImport = */ true)) | |||
7398 | return std::move(Err); | |||
7399 | ||||
7400 | auto ToCallOpOrErr = import(E->getCallOperator()); | |||
7401 | if (!ToCallOpOrErr) | |||
7402 | return ToCallOpOrErr.takeError(); | |||
7403 | ||||
7404 | ToClass->completeDefinition(); | |||
7405 | ||||
7406 | SmallVector<LambdaCapture, 8> ToCaptures; | |||
7407 | ToCaptures.reserve(E->capture_size()); | |||
7408 | for (const auto &FromCapture : E->captures()) { | |||
7409 | if (auto ToCaptureOrErr = import(FromCapture)) | |||
7410 | ToCaptures.push_back(*ToCaptureOrErr); | |||
7411 | else | |||
7412 | return ToCaptureOrErr.takeError(); | |||
7413 | } | |||
7414 | ||||
7415 | SmallVector<Expr *, 8> ToCaptureInits(E->capture_size()); | |||
7416 | if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits)) | |||
7417 | return std::move(Err); | |||
7418 | ||||
7419 | auto Imp = importSeq( | |||
7420 | E->getIntroducerRange(), E->getCaptureDefaultLoc(), E->getEndLoc()); | |||
7421 | if (!Imp) | |||
7422 | return Imp.takeError(); | |||
7423 | ||||
7424 | SourceRange ToIntroducerRange; | |||
7425 | SourceLocation ToCaptureDefaultLoc, ToEndLoc; | |||
7426 | std::tie(ToIntroducerRange, ToCaptureDefaultLoc, ToEndLoc) = *Imp; | |||
7427 | ||||
7428 | return LambdaExpr::Create( | |||
7429 | Importer.getToContext(), ToClass, ToIntroducerRange, | |||
7430 | E->getCaptureDefault(), ToCaptureDefaultLoc, ToCaptures, | |||
7431 | E->hasExplicitParameters(), E->hasExplicitResultType(), ToCaptureInits, | |||
7432 | ToEndLoc, E->containsUnexpandedParameterPack()); | |||
7433 | } | |||
7434 | ||||
7435 | ||||
7436 | ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) { | |||
7437 | auto Imp = importSeq(E->getLBraceLoc(), E->getRBraceLoc(), E->getType()); | |||
7438 | if (!Imp) | |||
7439 | return Imp.takeError(); | |||
7440 | ||||
7441 | SourceLocation ToLBraceLoc, ToRBraceLoc; | |||
7442 | QualType ToType; | |||
7443 | std::tie(ToLBraceLoc, ToRBraceLoc, ToType) = *Imp; | |||
7444 | ||||
7445 | SmallVector<Expr *, 4> ToExprs(E->getNumInits()); | |||
7446 | if (Error Err = ImportContainerChecked(E->inits(), ToExprs)) | |||
7447 | return std::move(Err); | |||
7448 | ||||
7449 | ASTContext &ToCtx = Importer.getToContext(); | |||
7450 | InitListExpr *To = new (ToCtx) InitListExpr( | |||
7451 | ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc); | |||
7452 | To->setType(ToType); | |||
7453 | ||||
7454 | if (E->hasArrayFiller()) { | |||
7455 | if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller())) | |||
7456 | To->setArrayFiller(*ToFillerOrErr); | |||
7457 | else | |||
7458 | return ToFillerOrErr.takeError(); | |||
7459 | } | |||
7460 | ||||
7461 | if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) { | |||
7462 | if (auto ToFDOrErr = import(FromFD)) | |||
7463 | To->setInitializedFieldInUnion(*ToFDOrErr); | |||
7464 | else | |||
7465 | return ToFDOrErr.takeError(); | |||
7466 | } | |||
7467 | ||||
7468 | if (InitListExpr *SyntForm = E->getSyntacticForm()) { | |||
7469 | if (auto ToSyntFormOrErr = import(SyntForm)) | |||
7470 | To->setSyntacticForm(*ToSyntFormOrErr); | |||
7471 | else | |||
7472 | return ToSyntFormOrErr.takeError(); | |||
7473 | } | |||
7474 | ||||
7475 | // Copy InitListExprBitfields, which are not handled in the ctor of | |||
7476 | // InitListExpr. | |||
7477 | To->sawArrayRangeDesignator(E->hadArrayRangeDesignator()); | |||
7478 | ||||
7479 | return To; | |||
7480 | } | |||
7481 | ||||
7482 | ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr( | |||
7483 | CXXStdInitializerListExpr *E) { | |||
7484 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
7485 | if (!ToTypeOrErr) | |||
7486 | return ToTypeOrErr.takeError(); | |||
7487 | ||||
7488 | ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); | |||
7489 | if (!ToSubExprOrErr) | |||
7490 | return ToSubExprOrErr.takeError(); | |||
7491 | ||||
7492 | return new (Importer.getToContext()) CXXStdInitializerListExpr( | |||
7493 | *ToTypeOrErr, *ToSubExprOrErr); | |||
7494 | } | |||
7495 | ||||
7496 | ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr( | |||
7497 | CXXInheritedCtorInitExpr *E) { | |||
7498 | auto Imp = importSeq(E->getLocation(), E->getType(), E->getConstructor()); | |||
7499 | if (!Imp) | |||
7500 | return Imp.takeError(); | |||
7501 | ||||
7502 | SourceLocation ToLocation; | |||
7503 | QualType ToType; | |||
7504 | CXXConstructorDecl *ToConstructor; | |||
7505 | std::tie(ToLocation, ToType, ToConstructor) = *Imp; | |||
7506 | ||||
7507 | return new (Importer.getToContext()) CXXInheritedCtorInitExpr( | |||
7508 | ToLocation, ToType, ToConstructor, E->constructsVBase(), | |||
7509 | E->inheritedFromVBase()); | |||
7510 | } | |||
7511 | ||||
7512 | ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) { | |||
7513 | auto Imp = importSeq(E->getType(), E->getCommonExpr(), E->getSubExpr()); | |||
7514 | if (!Imp) | |||
7515 | return Imp.takeError(); | |||
7516 | ||||
7517 | QualType ToType; | |||
7518 | Expr *ToCommonExpr, *ToSubExpr; | |||
7519 | std::tie(ToType, ToCommonExpr, ToSubExpr) = *Imp; | |||
7520 | ||||
7521 | return new (Importer.getToContext()) ArrayInitLoopExpr( | |||
7522 | ToType, ToCommonExpr, ToSubExpr); | |||
7523 | } | |||
7524 | ||||
7525 | ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { | |||
7526 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
7527 | if (!ToTypeOrErr) | |||
7528 | return ToTypeOrErr.takeError(); | |||
7529 | return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr); | |||
7530 | } | |||
7531 | ||||
7532 | ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { | |||
7533 | ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc()); | |||
7534 | if (!ToBeginLocOrErr) | |||
7535 | return ToBeginLocOrErr.takeError(); | |||
7536 | ||||
7537 | auto ToFieldOrErr = import(E->getField()); | |||
7538 | if (!ToFieldOrErr) | |||
7539 | return ToFieldOrErr.takeError(); | |||
7540 | ||||
7541 | auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); | |||
7542 | if (!UsedContextOrErr) | |||
7543 | return UsedContextOrErr.takeError(); | |||
7544 | ||||
7545 | return CXXDefaultInitExpr::Create( | |||
7546 | Importer.getToContext(), *ToBeginLocOrErr, *ToFieldOrErr, *UsedContextOrErr); | |||
7547 | } | |||
7548 | ||||
7549 | ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) { | |||
7550 | auto Imp = importSeq( | |||
7551 | E->getType(), E->getSubExpr(), E->getTypeInfoAsWritten(), | |||
7552 | E->getOperatorLoc(), E->getRParenLoc(), E->getAngleBrackets()); | |||
7553 | if (!Imp) | |||
7554 | return Imp.takeError(); | |||
7555 | ||||
7556 | QualType ToType; | |||
7557 | Expr *ToSubExpr; | |||
7558 | TypeSourceInfo *ToTypeInfoAsWritten; | |||
7559 | SourceLocation ToOperatorLoc, ToRParenLoc; | |||
7560 | SourceRange ToAngleBrackets; | |||
7561 | std::tie( | |||
7562 | ToType, ToSubExpr, ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, | |||
7563 | ToAngleBrackets) = *Imp; | |||
7564 | ||||
7565 | ExprValueKind VK = E->getValueKind(); | |||
7566 | CastKind CK = E->getCastKind(); | |||
7567 | auto ToBasePathOrErr = ImportCastPath(E); | |||
7568 | if (!ToBasePathOrErr) | |||
7569 | return ToBasePathOrErr.takeError(); | |||
7570 | ||||
7571 | if (isa<CXXStaticCastExpr>(E)) { | |||
7572 | return CXXStaticCastExpr::Create( | |||
7573 | Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), | |||
7574 | ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); | |||
7575 | } else if (isa<CXXDynamicCastExpr>(E)) { | |||
7576 | return CXXDynamicCastExpr::Create( | |||
7577 | Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), | |||
7578 | ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); | |||
7579 | } else if (isa<CXXReinterpretCastExpr>(E)) { | |||
7580 | return CXXReinterpretCastExpr::Create( | |||
7581 | Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), | |||
7582 | ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); | |||
7583 | } else if (isa<CXXConstCastExpr>(E)) { | |||
7584 | return CXXConstCastExpr::Create( | |||
7585 | Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten, | |||
7586 | ToOperatorLoc, ToRParenLoc, ToAngleBrackets); | |||
7587 | } else { | |||
7588 | llvm_unreachable("Unknown cast type")::llvm::llvm_unreachable_internal("Unknown cast type", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 7588); | |||
7589 | return make_error<ImportError>(); | |||
7590 | } | |||
7591 | } | |||
7592 | ||||
7593 | ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr( | |||
7594 | SubstNonTypeTemplateParmExpr *E) { | |||
7595 | auto Imp = importSeq( | |||
7596 | E->getType(), E->getExprLoc(), E->getParameter(), E->getReplacement()); | |||
7597 | if (!Imp) | |||
7598 | return Imp.takeError(); | |||
7599 | ||||
7600 | QualType ToType; | |||
7601 | SourceLocation ToExprLoc; | |||
7602 | NonTypeTemplateParmDecl *ToParameter; | |||
7603 | Expr *ToReplacement; | |||
7604 | std::tie(ToType, ToExprLoc, ToParameter, ToReplacement) = *Imp; | |||
7605 | ||||
7606 | return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr( | |||
7607 | ToType, E->getValueKind(), ToExprLoc, ToParameter, ToReplacement); | |||
7608 | } | |||
7609 | ||||
7610 | ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) { | |||
7611 | auto Imp = importSeq( | |||
7612 | E->getType(), E->getBeginLoc(), E->getEndLoc()); | |||
7613 | if (!Imp) | |||
7614 | return Imp.takeError(); | |||
7615 | ||||
7616 | QualType ToType; | |||
7617 | SourceLocation ToBeginLoc, ToEndLoc; | |||
7618 | std::tie(ToType, ToBeginLoc, ToEndLoc) = *Imp; | |||
7619 | ||||
7620 | SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs()); | |||
7621 | if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs)) | |||
7622 | return std::move(Err); | |||
7623 | ||||
7624 | // According to Sema::BuildTypeTrait(), if E is value-dependent, | |||
7625 | // Value is always false. | |||
7626 | bool ToValue = (E->isValueDependent() ? false : E->getValue()); | |||
7627 | ||||
7628 | return TypeTraitExpr::Create( | |||
7629 | Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs, | |||
7630 | ToEndLoc, ToValue); | |||
7631 | } | |||
7632 | ||||
7633 | ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) { | |||
7634 | ExpectedType ToTypeOrErr = import(E->getType()); | |||
7635 | if (!ToTypeOrErr) | |||
7636 | return ToTypeOrErr.takeError(); | |||
7637 | ||||
7638 | auto ToSourceRangeOrErr = import(E->getSourceRange()); | |||
7639 | if (!ToSourceRangeOrErr) | |||
7640 | return ToSourceRangeOrErr.takeError(); | |||
7641 | ||||
7642 | if (E->isTypeOperand()) { | |||
7643 | if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo())) | |||
7644 | return new (Importer.getToContext()) CXXTypeidExpr( | |||
7645 | *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr); | |||
7646 | else | |||
7647 | return ToTSIOrErr.takeError(); | |||
7648 | } | |||
7649 | ||||
7650 | ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand()); | |||
7651 | if (!ToExprOperandOrErr) | |||
7652 | return ToExprOperandOrErr.takeError(); | |||
7653 | ||||
7654 | return new (Importer.getToContext()) CXXTypeidExpr( | |||
7655 | *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr); | |||
7656 | } | |||
7657 | ||||
7658 | void ASTNodeImporter::ImportOverrides(CXXMethodDecl *ToMethod, | |||
7659 | CXXMethodDecl *FromMethod) { | |||
7660 | for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) { | |||
7661 | if (auto ImportedOrErr = import(FromOverriddenMethod)) | |||
7662 | ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>( | |||
7663 | (*ImportedOrErr)->getCanonicalDecl())); | |||
7664 | else | |||
7665 | consumeError(ImportedOrErr.takeError()); | |||
7666 | } | |||
7667 | } | |||
7668 | ||||
7669 | ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, | |||
7670 | ASTContext &FromContext, FileManager &FromFileManager, | |||
7671 | bool MinimalImport, | |||
7672 | ASTImporterLookupTable *LookupTable) | |||
7673 | : LookupTable(LookupTable), ToContext(ToContext), FromContext(FromContext), | |||
7674 | ToFileManager(ToFileManager), FromFileManager(FromFileManager), | |||
7675 | Minimal(MinimalImport) { | |||
7676 | ||||
7677 | ImportedDecls[FromContext.getTranslationUnitDecl()] = | |||
7678 | ToContext.getTranslationUnitDecl(); | |||
7679 | } | |||
7680 | ||||
7681 | ASTImporter::~ASTImporter() = default; | |||
7682 | ||||
7683 | Optional<unsigned> ASTImporter::getFieldIndex(Decl *F) { | |||
7684 | assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&((F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl >(*F)) && "Try to get field index for non-field.") ? static_cast<void> (0) : __assert_fail ("F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) && \"Try to get field index for non-field.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 7685, __PRETTY_FUNCTION__)) | |||
7685 | "Try to get field index for non-field.")((F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl >(*F)) && "Try to get field index for non-field.") ? static_cast<void> (0) : __assert_fail ("F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) && \"Try to get field index for non-field.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 7685, __PRETTY_FUNCTION__)); | |||
7686 | ||||
7687 | auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext()); | |||
7688 | if (!Owner) | |||
7689 | return None; | |||
7690 | ||||
7691 | unsigned Index = 0; | |||
7692 | for (const auto *D : Owner->decls()) { | |||
7693 | if (D == F) | |||
7694 | return Index; | |||
7695 | ||||
7696 | if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) | |||
7697 | ++Index; | |||
7698 | } | |||
7699 | ||||
7700 | llvm_unreachable("Field was not found in its parent context.")::llvm::llvm_unreachable_internal("Field was not found in its parent context." , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 7700); | |||
7701 | ||||
7702 | return None; | |||
7703 | } | |||
7704 | ||||
7705 | ASTImporter::FoundDeclsTy | |||
7706 | ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) { | |||
7707 | // We search in the redecl context because of transparent contexts. | |||
7708 | // E.g. a simple C language enum is a transparent context: | |||
7709 | // enum E { A, B }; | |||
7710 | // Now if we had a global variable in the TU | |||
7711 | // int A; | |||
7712 | // then the enum constant 'A' and the variable 'A' violates ODR. | |||
7713 | // We can diagnose this only if we search in the redecl context. | |||
7714 | DeclContext *ReDC = DC->getRedeclContext(); | |||
7715 | if (LookupTable) { | |||
7716 | ASTImporterLookupTable::LookupResult LookupResult = | |||
7717 | LookupTable->lookup(ReDC, Name); | |||
7718 | return FoundDeclsTy(LookupResult.begin(), LookupResult.end()); | |||
7719 | } else { | |||
7720 | // FIXME Can we remove this kind of lookup? | |||
7721 | // Or lldb really needs this C/C++ lookup? | |||
7722 | FoundDeclsTy Result; | |||
7723 | ReDC->localUncachedLookup(Name, Result); | |||
7724 | return Result; | |||
7725 | } | |||
7726 | } | |||
7727 | ||||
7728 | void ASTImporter::AddToLookupTable(Decl *ToD) { | |||
7729 | if (LookupTable) | |||
7730 | if (auto *ToND = dyn_cast<NamedDecl>(ToD)) | |||
7731 | LookupTable->add(ToND); | |||
7732 | } | |||
7733 | ||||
7734 | Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) { | |||
7735 | // Import the decl using ASTNodeImporter. | |||
7736 | ASTNodeImporter Importer(*this); | |||
7737 | return Importer.Visit(FromD); | |||
7738 | } | |||
7739 | ||||
7740 | void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) { | |||
7741 | MapImported(FromD, ToD); | |||
7742 | AddToLookupTable(ToD); | |||
7743 | } | |||
7744 | ||||
7745 | Expected<QualType> ASTImporter::Import(QualType FromT) { | |||
7746 | if (FromT.isNull()) | |||
7747 | return QualType{}; | |||
7748 | ||||
7749 | const Type *FromTy = FromT.getTypePtr(); | |||
7750 | ||||
7751 | // Check whether we've already imported this type. | |||
7752 | llvm::DenseMap<const Type *, const Type *>::iterator Pos | |||
7753 | = ImportedTypes.find(FromTy); | |||
7754 | if (Pos != ImportedTypes.end()) | |||
7755 | return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers()); | |||
7756 | ||||
7757 | // Import the type | |||
7758 | ASTNodeImporter Importer(*this); | |||
7759 | ExpectedType ToTOrErr = Importer.Visit(FromTy); | |||
7760 | if (!ToTOrErr) | |||
7761 | return ToTOrErr.takeError(); | |||
7762 | ||||
7763 | // Record the imported type. | |||
7764 | ImportedTypes[FromTy] = (*ToTOrErr).getTypePtr(); | |||
7765 | ||||
7766 | return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers()); | |||
7767 | } | |||
7768 | ||||
7769 | Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) { | |||
7770 | if (!FromTSI) | |||
7771 | return FromTSI; | |||
7772 | ||||
7773 | // FIXME: For now we just create a "trivial" type source info based | |||
7774 | // on the type and a single location. Implement a real version of this. | |||
7775 | ExpectedType TOrErr = Import(FromTSI->getType()); | |||
7776 | if (!TOrErr) | |||
7777 | return TOrErr.takeError(); | |||
7778 | ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc()); | |||
7779 | if (!BeginLocOrErr) | |||
7780 | return BeginLocOrErr.takeError(); | |||
7781 | ||||
7782 | return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr); | |||
7783 | } | |||
7784 | ||||
7785 | Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) { | |||
7786 | Attr *ToAttr = FromAttr->clone(ToContext); | |||
7787 | if (auto ToRangeOrErr = Import(FromAttr->getRange())) | |||
7788 | ToAttr->setRange(*ToRangeOrErr); | |||
7789 | else | |||
7790 | return ToRangeOrErr.takeError(); | |||
7791 | ||||
7792 | return ToAttr; | |||
7793 | } | |||
7794 | ||||
7795 | Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const { | |||
7796 | auto Pos = ImportedDecls.find(FromD); | |||
7797 | if (Pos != ImportedDecls.end()) | |||
7798 | return Pos->second; | |||
7799 | else | |||
7800 | return nullptr; | |||
7801 | } | |||
7802 | ||||
7803 | TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) { | |||
7804 | auto FromDPos = ImportedFromDecls.find(ToD); | |||
7805 | if (FromDPos == ImportedFromDecls.end()) | |||
7806 | return nullptr; | |||
7807 | return FromDPos->second->getTranslationUnitDecl(); | |||
7808 | } | |||
7809 | ||||
7810 | Expected<Decl *> ASTImporter::Import(Decl *FromD) { | |||
7811 | if (!FromD) | |||
7812 | return nullptr; | |||
7813 | ||||
7814 | ||||
7815 | // Check whether we've already imported this declaration. | |||
7816 | Decl *ToD = GetAlreadyImportedOrNull(FromD); | |||
7817 | if (ToD) { | |||
7818 | // If FromD has some updated flags after last import, apply it | |||
7819 | updateFlags(FromD, ToD); | |||
7820 | return ToD; | |||
7821 | } | |||
7822 | ||||
7823 | // Import the declaration. | |||
7824 | ExpectedDecl ToDOrErr = ImportImpl(FromD); | |||
7825 | if (!ToDOrErr) | |||
7826 | return ToDOrErr; | |||
7827 | ToD = *ToDOrErr; | |||
7828 | ||||
7829 | // FIXME Use getImportDeclErrorIfAny() here (and return with the error) once | |||
7830 | // the error handling is finished in GetImportedOrCreateSpecialDecl(). | |||
7831 | if (!ToD) { | |||
7832 | return nullptr; | |||
7833 | } | |||
7834 | ||||
7835 | // Make sure that ImportImpl registered the imported decl. | |||
7836 | assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?")((ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?" ) ? static_cast<void> (0) : __assert_fail ("ImportedDecls.count(FromD) != 0 && \"Missing call to MapImported?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 7836, __PRETTY_FUNCTION__)); | |||
7837 | ||||
7838 | // Once the decl is connected to the existing declarations, i.e. when the | |||
7839 | // redecl chain is properly set then we populate the lookup again. | |||
7840 | // This way the primary context will be able to find all decls. | |||
7841 | AddToLookupTable(ToD); | |||
7842 | ||||
7843 | // Notify subclasses. | |||
7844 | Imported(FromD, ToD); | |||
7845 | ||||
7846 | updateFlags(FromD, ToD); | |||
7847 | return ToDOrErr; | |||
7848 | } | |||
7849 | ||||
7850 | Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) { | |||
7851 | if (!FromDC) | |||
7852 | return FromDC; | |||
7853 | ||||
7854 | ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC)); | |||
7855 | if (!ToDCOrErr) | |||
7856 | return ToDCOrErr.takeError(); | |||
7857 | auto *ToDC = cast<DeclContext>(*ToDCOrErr); | |||
7858 | ||||
7859 | // When we're using a record/enum/Objective-C class/protocol as a context, we | |||
7860 | // need it to have a definition. | |||
7861 | if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) { | |||
7862 | auto *FromRecord = cast<RecordDecl>(FromDC); | |||
7863 | if (ToRecord->isCompleteDefinition()) { | |||
7864 | // Do nothing. | |||
7865 | } else if (FromRecord->isCompleteDefinition()) { | |||
7866 | if (Error Err = ASTNodeImporter(*this).ImportDefinition( | |||
7867 | FromRecord, ToRecord, ASTNodeImporter::IDK_Basic)) | |||
7868 | return std::move(Err); | |||
7869 | } else { | |||
7870 | CompleteDecl(ToRecord); | |||
7871 | } | |||
7872 | } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) { | |||
7873 | auto *FromEnum = cast<EnumDecl>(FromDC); | |||
7874 | if (ToEnum->isCompleteDefinition()) { | |||
7875 | // Do nothing. | |||
7876 | } else if (FromEnum->isCompleteDefinition()) { | |||
7877 | if (Error Err = ASTNodeImporter(*this).ImportDefinition( | |||
7878 | FromEnum, ToEnum, ASTNodeImporter::IDK_Basic)) | |||
7879 | return std::move(Err); | |||
7880 | } else { | |||
7881 | CompleteDecl(ToEnum); | |||
7882 | } | |||
7883 | } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) { | |||
7884 | auto *FromClass = cast<ObjCInterfaceDecl>(FromDC); | |||
7885 | if (ToClass->getDefinition()) { | |||
7886 | // Do nothing. | |||
7887 | } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) { | |||
7888 | if (Error Err = ASTNodeImporter(*this).ImportDefinition( | |||
7889 | FromDef, ToClass, ASTNodeImporter::IDK_Basic)) | |||
7890 | return std::move(Err); | |||
7891 | } else { | |||
7892 | CompleteDecl(ToClass); | |||
7893 | } | |||
7894 | } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) { | |||
7895 | auto *FromProto = cast<ObjCProtocolDecl>(FromDC); | |||
7896 | if (ToProto->getDefinition()) { | |||
7897 | // Do nothing. | |||
7898 | } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) { | |||
7899 | if (Error Err = ASTNodeImporter(*this).ImportDefinition( | |||
7900 | FromDef, ToProto, ASTNodeImporter::IDK_Basic)) | |||
7901 | return std::move(Err); | |||
7902 | } else { | |||
7903 | CompleteDecl(ToProto); | |||
7904 | } | |||
7905 | } | |||
7906 | ||||
7907 | return ToDC; | |||
7908 | } | |||
7909 | ||||
7910 | Expected<Expr *> ASTImporter::Import(Expr *FromE) { | |||
7911 | if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE))) | |||
7912 | return cast_or_null<Expr>(*ToSOrErr); | |||
7913 | else | |||
7914 | return ToSOrErr.takeError(); | |||
7915 | } | |||
7916 | ||||
7917 | Expected<Stmt *> ASTImporter::Import(Stmt *FromS) { | |||
7918 | if (!FromS) | |||
7919 | return nullptr; | |||
7920 | ||||
7921 | // Check whether we've already imported this statement. | |||
7922 | llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS); | |||
7923 | if (Pos != ImportedStmts.end()) | |||
7924 | return Pos->second; | |||
7925 | ||||
7926 | // Import the statement. | |||
7927 | ASTNodeImporter Importer(*this); | |||
7928 | ExpectedStmt ToSOrErr = Importer.Visit(FromS); | |||
7929 | if (!ToSOrErr) | |||
7930 | return ToSOrErr; | |||
7931 | ||||
7932 | if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) { | |||
7933 | auto *FromE = cast<Expr>(FromS); | |||
7934 | // Copy ExprBitfields, which may not be handled in Expr subclasses | |||
7935 | // constructors. | |||
7936 | ToE->setValueKind(FromE->getValueKind()); | |||
7937 | ToE->setObjectKind(FromE->getObjectKind()); | |||
7938 | ToE->setTypeDependent(FromE->isTypeDependent()); | |||
7939 | ToE->setValueDependent(FromE->isValueDependent()); | |||
7940 | ToE->setInstantiationDependent(FromE->isInstantiationDependent()); | |||
7941 | ToE->setContainsUnexpandedParameterPack( | |||
7942 | FromE->containsUnexpandedParameterPack()); | |||
7943 | } | |||
7944 | ||||
7945 | // Record the imported statement object. | |||
7946 | ImportedStmts[FromS] = *ToSOrErr; | |||
7947 | return ToSOrErr; | |||
7948 | } | |||
7949 | ||||
7950 | Expected<NestedNameSpecifier *> | |||
7951 | ASTImporter::Import(NestedNameSpecifier *FromNNS) { | |||
7952 | if (!FromNNS) | |||
7953 | return nullptr; | |||
7954 | ||||
7955 | NestedNameSpecifier *Prefix; | |||
7956 | if (Error Err = importInto(Prefix, FromNNS->getPrefix())) | |||
7957 | return std::move(Err); | |||
7958 | ||||
7959 | switch (FromNNS->getKind()) { | |||
7960 | case NestedNameSpecifier::Identifier: | |||
7961 | assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.")((FromNNS->getAsIdentifier() && "NNS should contain identifier." ) ? static_cast<void> (0) : __assert_fail ("FromNNS->getAsIdentifier() && \"NNS should contain identifier.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 7961, __PRETTY_FUNCTION__)); | |||
7962 | return NestedNameSpecifier::Create(ToContext, Prefix, | |||
7963 | Import(FromNNS->getAsIdentifier())); | |||
7964 | ||||
7965 | case NestedNameSpecifier::Namespace: | |||
7966 | if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) { | |||
7967 | return NestedNameSpecifier::Create(ToContext, Prefix, | |||
7968 | cast<NamespaceDecl>(*NSOrErr)); | |||
7969 | } else | |||
7970 | return NSOrErr.takeError(); | |||
7971 | ||||
7972 | case NestedNameSpecifier::NamespaceAlias: | |||
7973 | if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias())) | |||
7974 | return NestedNameSpecifier::Create(ToContext, Prefix, | |||
7975 | cast<NamespaceAliasDecl>(*NSADOrErr)); | |||
7976 | else | |||
7977 | return NSADOrErr.takeError(); | |||
7978 | ||||
7979 | case NestedNameSpecifier::Global: | |||
7980 | return NestedNameSpecifier::GlobalSpecifier(ToContext); | |||
7981 | ||||
7982 | case NestedNameSpecifier::Super: | |||
7983 | if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl())) | |||
7984 | return NestedNameSpecifier::SuperSpecifier(ToContext, | |||
7985 | cast<CXXRecordDecl>(*RDOrErr)); | |||
7986 | else | |||
7987 | return RDOrErr.takeError(); | |||
7988 | ||||
7989 | case NestedNameSpecifier::TypeSpec: | |||
7990 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
7991 | if (Expected<QualType> TyOrErr = | |||
7992 | Import(QualType(FromNNS->getAsType(), 0u))) { | |||
7993 | bool TSTemplate = | |||
7994 | FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate; | |||
7995 | return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate, | |||
7996 | TyOrErr->getTypePtr()); | |||
7997 | } else { | |||
7998 | return TyOrErr.takeError(); | |||
7999 | } | |||
8000 | } | |||
8001 | ||||
8002 | llvm_unreachable("Invalid nested name specifier kind")::llvm::llvm_unreachable_internal("Invalid nested name specifier kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 8002); | |||
8003 | } | |||
8004 | ||||
8005 | Expected<NestedNameSpecifierLoc> | |||
8006 | ASTImporter::Import(NestedNameSpecifierLoc FromNNS) { | |||
8007 | // Copied from NestedNameSpecifier mostly. | |||
8008 | SmallVector<NestedNameSpecifierLoc , 8> NestedNames; | |||
8009 | NestedNameSpecifierLoc NNS = FromNNS; | |||
8010 | ||||
8011 | // Push each of the nested-name-specifiers's onto a stack for | |||
8012 | // serialization in reverse order. | |||
8013 | while (NNS) { | |||
8014 | NestedNames.push_back(NNS); | |||
8015 | NNS = NNS.getPrefix(); | |||
8016 | } | |||
8017 | ||||
8018 | NestedNameSpecifierLocBuilder Builder; | |||
8019 | ||||
8020 | while (!NestedNames.empty()) { | |||
8021 | NNS = NestedNames.pop_back_val(); | |||
8022 | NestedNameSpecifier *Spec = nullptr; | |||
8023 | if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier())) | |||
8024 | return std::move(Err); | |||
8025 | ||||
8026 | NestedNameSpecifier::SpecifierKind Kind = Spec->getKind(); | |||
8027 | ||||
8028 | SourceLocation ToLocalBeginLoc, ToLocalEndLoc; | |||
8029 | if (Kind != NestedNameSpecifier::Super) { | |||
8030 | if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc())) | |||
8031 | return std::move(Err); | |||
8032 | ||||
8033 | if (Kind != NestedNameSpecifier::Global) | |||
8034 | if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc())) | |||
8035 | return std::move(Err); | |||
8036 | } | |||
8037 | ||||
8038 | switch (Kind) { | |||
8039 | case NestedNameSpecifier::Identifier: | |||
8040 | Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc, | |||
8041 | ToLocalEndLoc); | |||
8042 | break; | |||
8043 | ||||
8044 | case NestedNameSpecifier::Namespace: | |||
8045 | Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc, | |||
8046 | ToLocalEndLoc); | |||
8047 | break; | |||
8048 | ||||
8049 | case NestedNameSpecifier::NamespaceAlias: | |||
8050 | Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(), | |||
8051 | ToLocalBeginLoc, ToLocalEndLoc); | |||
8052 | break; | |||
8053 | ||||
8054 | case NestedNameSpecifier::TypeSpec: | |||
8055 | case NestedNameSpecifier::TypeSpecWithTemplate: { | |||
8056 | SourceLocation ToTLoc; | |||
8057 | if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc())) | |||
8058 | return std::move(Err); | |||
8059 | TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo( | |||
8060 | QualType(Spec->getAsType(), 0), ToTLoc); | |||
8061 | Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(), | |||
8062 | ToLocalEndLoc); | |||
8063 | break; | |||
8064 | } | |||
8065 | ||||
8066 | case NestedNameSpecifier::Global: | |||
8067 | Builder.MakeGlobal(getToContext(), ToLocalBeginLoc); | |||
8068 | break; | |||
8069 | ||||
8070 | case NestedNameSpecifier::Super: { | |||
8071 | auto ToSourceRangeOrErr = Import(NNS.getSourceRange()); | |||
8072 | if (!ToSourceRangeOrErr) | |||
8073 | return ToSourceRangeOrErr.takeError(); | |||
8074 | ||||
8075 | Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(), | |||
8076 | ToSourceRangeOrErr->getBegin(), | |||
8077 | ToSourceRangeOrErr->getEnd()); | |||
8078 | } | |||
8079 | } | |||
8080 | } | |||
8081 | ||||
8082 | return Builder.getWithLocInContext(getToContext()); | |||
8083 | } | |||
8084 | ||||
8085 | Expected<TemplateName> ASTImporter::Import(TemplateName From) { | |||
8086 | switch (From.getKind()) { | |||
8087 | case TemplateName::Template: | |||
8088 | if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl())) | |||
8089 | return TemplateName(cast<TemplateDecl>(*ToTemplateOrErr)); | |||
8090 | else | |||
8091 | return ToTemplateOrErr.takeError(); | |||
8092 | ||||
8093 | case TemplateName::OverloadedTemplate: { | |||
8094 | OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate(); | |||
8095 | UnresolvedSet<2> ToTemplates; | |||
8096 | for (auto *I : *FromStorage) { | |||
8097 | if (auto ToOrErr = Import(I)) | |||
8098 | ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr)); | |||
8099 | else | |||
8100 | return ToOrErr.takeError(); | |||
8101 | } | |||
8102 | return ToContext.getOverloadedTemplateName(ToTemplates.begin(), | |||
8103 | ToTemplates.end()); | |||
8104 | } | |||
8105 | ||||
8106 | case TemplateName::AssumedTemplate: { | |||
8107 | AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName(); | |||
8108 | auto DeclNameOrErr = Import(FromStorage->getDeclName()); | |||
8109 | if (!DeclNameOrErr) | |||
8110 | return DeclNameOrErr.takeError(); | |||
8111 | return ToContext.getAssumedTemplateName(*DeclNameOrErr); | |||
8112 | } | |||
8113 | ||||
8114 | case TemplateName::QualifiedTemplate: { | |||
8115 | QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName(); | |||
8116 | auto QualifierOrErr = Import(QTN->getQualifier()); | |||
8117 | if (!QualifierOrErr) | |||
8118 | return QualifierOrErr.takeError(); | |||
8119 | ||||
8120 | if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl())) | |||
8121 | return ToContext.getQualifiedTemplateName( | |||
8122 | *QualifierOrErr, QTN->hasTemplateKeyword(), | |||
8123 | cast<TemplateDecl>(*ToTemplateOrErr)); | |||
8124 | else | |||
8125 | return ToTemplateOrErr.takeError(); | |||
8126 | } | |||
8127 | ||||
8128 | case TemplateName::DependentTemplate: { | |||
8129 | DependentTemplateName *DTN = From.getAsDependentTemplateName(); | |||
8130 | auto QualifierOrErr = Import(DTN->getQualifier()); | |||
8131 | if (!QualifierOrErr) | |||
8132 | return QualifierOrErr.takeError(); | |||
8133 | ||||
8134 | if (DTN->isIdentifier()) { | |||
8135 | return ToContext.getDependentTemplateName(*QualifierOrErr, | |||
8136 | Import(DTN->getIdentifier())); | |||
8137 | } | |||
8138 | ||||
8139 | return ToContext.getDependentTemplateName(*QualifierOrErr, | |||
8140 | DTN->getOperator()); | |||
8141 | } | |||
8142 | ||||
8143 | case TemplateName::SubstTemplateTemplateParm: { | |||
8144 | SubstTemplateTemplateParmStorage *Subst = | |||
8145 | From.getAsSubstTemplateTemplateParm(); | |||
8146 | ExpectedDecl ParamOrErr = Import(Subst->getParameter()); | |||
8147 | if (!ParamOrErr) | |||
8148 | return ParamOrErr.takeError(); | |||
8149 | ||||
8150 | auto ReplacementOrErr = Import(Subst->getReplacement()); | |||
8151 | if (!ReplacementOrErr) | |||
8152 | return ReplacementOrErr.takeError(); | |||
8153 | ||||
8154 | return ToContext.getSubstTemplateTemplateParm( | |||
8155 | cast<TemplateTemplateParmDecl>(*ParamOrErr), *ReplacementOrErr); | |||
8156 | } | |||
8157 | ||||
8158 | case TemplateName::SubstTemplateTemplateParmPack: { | |||
8159 | SubstTemplateTemplateParmPackStorage *SubstPack | |||
8160 | = From.getAsSubstTemplateTemplateParmPack(); | |||
8161 | ExpectedDecl ParamOrErr = Import(SubstPack->getParameterPack()); | |||
8162 | if (!ParamOrErr) | |||
8163 | return ParamOrErr.takeError(); | |||
8164 | ||||
8165 | ASTNodeImporter Importer(*this); | |||
8166 | auto ArgPackOrErr = | |||
8167 | Importer.ImportTemplateArgument(SubstPack->getArgumentPack()); | |||
8168 | if (!ArgPackOrErr) | |||
8169 | return ArgPackOrErr.takeError(); | |||
8170 | ||||
8171 | return ToContext.getSubstTemplateTemplateParmPack( | |||
8172 | cast<TemplateTemplateParmDecl>(*ParamOrErr), *ArgPackOrErr); | |||
8173 | } | |||
8174 | } | |||
8175 | ||||
8176 | llvm_unreachable("Invalid template name kind")::llvm::llvm_unreachable_internal("Invalid template name kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 8176); | |||
8177 | } | |||
8178 | ||||
8179 | Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) { | |||
8180 | if (FromLoc.isInvalid()) | |||
8181 | return SourceLocation{}; | |||
8182 | ||||
8183 | SourceManager &FromSM = FromContext.getSourceManager(); | |||
8184 | bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc); | |||
8185 | ||||
8186 | std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc); | |||
8187 | Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin); | |||
8188 | if (!ToFileIDOrErr) | |||
8189 | return ToFileIDOrErr.takeError(); | |||
8190 | SourceManager &ToSM = ToContext.getSourceManager(); | |||
8191 | return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second); | |||
8192 | } | |||
8193 | ||||
8194 | Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) { | |||
8195 | SourceLocation ToBegin, ToEnd; | |||
8196 | if (Error Err = importInto(ToBegin, FromRange.getBegin())) | |||
8197 | return std::move(Err); | |||
8198 | if (Error Err = importInto(ToEnd, FromRange.getEnd())) | |||
8199 | return std::move(Err); | |||
8200 | ||||
8201 | return SourceRange(ToBegin, ToEnd); | |||
8202 | } | |||
8203 | ||||
8204 | Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) { | |||
8205 | llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID); | |||
8206 | if (Pos != ImportedFileIDs.end()) | |||
8207 | return Pos->second; | |||
8208 | ||||
8209 | SourceManager &FromSM = FromContext.getSourceManager(); | |||
8210 | SourceManager &ToSM = ToContext.getSourceManager(); | |||
8211 | const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID); | |||
8212 | ||||
8213 | // Map the FromID to the "to" source manager. | |||
8214 | FileID ToID; | |||
8215 | if (FromSLoc.isExpansion()) { | |||
8216 | const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion(); | |||
8217 | ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc()); | |||
8218 | if (!ToSpLoc) | |||
8219 | return ToSpLoc.takeError(); | |||
8220 | ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart()); | |||
8221 | if (!ToExLocS) | |||
8222 | return ToExLocS.takeError(); | |||
8223 | unsigned TokenLen = FromSM.getFileIDSize(FromID); | |||
8224 | SourceLocation MLoc; | |||
8225 | if (FromEx.isMacroArgExpansion()) { | |||
8226 | MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, TokenLen); | |||
8227 | } else { | |||
8228 | if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd())) | |||
8229 | MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, TokenLen, | |||
8230 | FromEx.isExpansionTokenRange()); | |||
8231 | else | |||
8232 | return ToExLocE.takeError(); | |||
8233 | } | |||
8234 | ToID = ToSM.getFileID(MLoc); | |||
8235 | } else { | |||
8236 | const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache(); | |||
8237 | ||||
8238 | if (!IsBuiltin) { | |||
8239 | // Include location of this file. | |||
8240 | ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc()); | |||
8241 | if (!ToIncludeLoc) | |||
8242 | return ToIncludeLoc.takeError(); | |||
8243 | ||||
8244 | if (Cache->OrigEntry && Cache->OrigEntry->getDir()) { | |||
8245 | // FIXME: We probably want to use getVirtualFile(), so we don't hit the | |||
8246 | // disk again | |||
8247 | // FIXME: We definitely want to re-use the existing MemoryBuffer, rather | |||
8248 | // than mmap the files several times. | |||
8249 | const FileEntry *Entry = | |||
8250 | ToFileManager.getFile(Cache->OrigEntry->getName()); | |||
8251 | // FIXME: The filename may be a virtual name that does probably not | |||
8252 | // point to a valid file and we get no Entry here. In this case try with | |||
8253 | // the memory buffer below. | |||
8254 | if (Entry) | |||
8255 | ToID = ToSM.createFileID(Entry, *ToIncludeLoc, | |||
8256 | FromSLoc.getFile().getFileCharacteristic()); | |||
8257 | } | |||
8258 | } | |||
8259 | ||||
8260 | if (ToID.isInvalid() || IsBuiltin) { | |||
8261 | // FIXME: We want to re-use the existing MemoryBuffer! | |||
8262 | bool Invalid = true; | |||
8263 | const llvm::MemoryBuffer *FromBuf = Cache->getBuffer( | |||
8264 | FromContext.getDiagnostics(), FromSM, SourceLocation{}, &Invalid); | |||
8265 | if (!FromBuf || Invalid) | |||
8266 | // FIXME: Use a new error kind? | |||
8267 | return llvm::make_error<ImportError>(ImportError::Unknown); | |||
8268 | ||||
8269 | std::unique_ptr<llvm::MemoryBuffer> ToBuf = | |||
8270 | llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(), | |||
8271 | FromBuf->getBufferIdentifier()); | |||
8272 | ToID = ToSM.createFileID(std::move(ToBuf), | |||
8273 | FromSLoc.getFile().getFileCharacteristic()); | |||
8274 | } | |||
8275 | } | |||
8276 | ||||
8277 | assert(ToID.isValid() && "Unexpected invalid fileID was created.")((ToID.isValid() && "Unexpected invalid fileID was created." ) ? static_cast<void> (0) : __assert_fail ("ToID.isValid() && \"Unexpected invalid fileID was created.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 8277, __PRETTY_FUNCTION__)); | |||
8278 | ||||
8279 | ImportedFileIDs[FromID] = ToID; | |||
8280 | return ToID; | |||
8281 | } | |||
8282 | ||||
8283 | Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) { | |||
8284 | ExpectedExpr ToExprOrErr = Import(From->getInit()); | |||
8285 | if (!ToExprOrErr) | |||
8286 | return ToExprOrErr.takeError(); | |||
8287 | ||||
8288 | auto LParenLocOrErr = Import(From->getLParenLoc()); | |||
8289 | if (!LParenLocOrErr) | |||
8290 | return LParenLocOrErr.takeError(); | |||
8291 | ||||
8292 | auto RParenLocOrErr = Import(From->getRParenLoc()); | |||
8293 | if (!RParenLocOrErr) | |||
8294 | return RParenLocOrErr.takeError(); | |||
8295 | ||||
8296 | if (From->isBaseInitializer()) { | |||
8297 | auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); | |||
8298 | if (!ToTInfoOrErr) | |||
8299 | return ToTInfoOrErr.takeError(); | |||
8300 | ||||
8301 | SourceLocation EllipsisLoc; | |||
8302 | if (From->isPackExpansion()) | |||
8303 | if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc())) | |||
8304 | return std::move(Err); | |||
8305 | ||||
8306 | return new (ToContext) CXXCtorInitializer( | |||
8307 | ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr, | |||
8308 | *ToExprOrErr, *RParenLocOrErr, EllipsisLoc); | |||
8309 | } else if (From->isMemberInitializer()) { | |||
8310 | ExpectedDecl ToFieldOrErr = Import(From->getMember()); | |||
8311 | if (!ToFieldOrErr) | |||
8312 | return ToFieldOrErr.takeError(); | |||
8313 | ||||
8314 | auto MemberLocOrErr = Import(From->getMemberLocation()); | |||
8315 | if (!MemberLocOrErr) | |||
8316 | return MemberLocOrErr.takeError(); | |||
8317 | ||||
8318 | return new (ToContext) CXXCtorInitializer( | |||
8319 | ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr, | |||
8320 | *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); | |||
8321 | } else if (From->isIndirectMemberInitializer()) { | |||
8322 | ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember()); | |||
8323 | if (!ToIFieldOrErr) | |||
8324 | return ToIFieldOrErr.takeError(); | |||
8325 | ||||
8326 | auto MemberLocOrErr = Import(From->getMemberLocation()); | |||
8327 | if (!MemberLocOrErr) | |||
8328 | return MemberLocOrErr.takeError(); | |||
8329 | ||||
8330 | return new (ToContext) CXXCtorInitializer( | |||
8331 | ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr), | |||
8332 | *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); | |||
8333 | } else if (From->isDelegatingInitializer()) { | |||
8334 | auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); | |||
8335 | if (!ToTInfoOrErr) | |||
8336 | return ToTInfoOrErr.takeError(); | |||
8337 | ||||
8338 | return new (ToContext) | |||
8339 | CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr, | |||
8340 | *ToExprOrErr, *RParenLocOrErr); | |||
8341 | } else { | |||
8342 | // FIXME: assert? | |||
8343 | return make_error<ImportError>(); | |||
8344 | } | |||
8345 | } | |||
8346 | ||||
8347 | Expected<CXXBaseSpecifier *> | |||
8348 | ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) { | |||
8349 | auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec); | |||
8350 | if (Pos != ImportedCXXBaseSpecifiers.end()) | |||
8351 | return Pos->second; | |||
8352 | ||||
8353 | Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange()); | |||
8354 | if (!ToSourceRange) | |||
8355 | return ToSourceRange.takeError(); | |||
8356 | Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo()); | |||
8357 | if (!ToTSI) | |||
8358 | return ToTSI.takeError(); | |||
8359 | ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc()); | |||
8360 | if (!ToEllipsisLoc) | |||
8361 | return ToEllipsisLoc.takeError(); | |||
8362 | CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier( | |||
8363 | *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(), | |||
8364 | BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc); | |||
8365 | ImportedCXXBaseSpecifiers[BaseSpec] = Imported; | |||
8366 | return Imported; | |||
8367 | } | |||
8368 | ||||
8369 | Error ASTImporter::ImportDefinition(Decl *From) { | |||
8370 | ExpectedDecl ToOrErr = Import(From); | |||
8371 | if (!ToOrErr) | |||
8372 | return ToOrErr.takeError(); | |||
8373 | Decl *To = *ToOrErr; | |||
8374 | ||||
8375 | auto *FromDC = cast<DeclContext>(From); | |||
8376 | ASTNodeImporter Importer(*this); | |||
8377 | ||||
8378 | if (auto *ToRecord = dyn_cast<RecordDecl>(To)) { | |||
8379 | if (!ToRecord->getDefinition()) { | |||
8380 | return Importer.ImportDefinition( | |||
8381 | cast<RecordDecl>(FromDC), ToRecord, | |||
8382 | ASTNodeImporter::IDK_Everything); | |||
8383 | } | |||
8384 | } | |||
8385 | ||||
8386 | if (auto *ToEnum = dyn_cast<EnumDecl>(To)) { | |||
8387 | if (!ToEnum->getDefinition()) { | |||
8388 | return Importer.ImportDefinition( | |||
8389 | cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); | |||
8390 | } | |||
8391 | } | |||
8392 | ||||
8393 | if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) { | |||
8394 | if (!ToIFace->getDefinition()) { | |||
8395 | return Importer.ImportDefinition( | |||
8396 | cast<ObjCInterfaceDecl>(FromDC), ToIFace, | |||
8397 | ASTNodeImporter::IDK_Everything); | |||
8398 | } | |||
8399 | } | |||
8400 | ||||
8401 | if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) { | |||
8402 | if (!ToProto->getDefinition()) { | |||
8403 | return Importer.ImportDefinition( | |||
8404 | cast<ObjCProtocolDecl>(FromDC), ToProto, | |||
8405 | ASTNodeImporter::IDK_Everything); | |||
8406 | } | |||
8407 | } | |||
8408 | ||||
8409 | return Importer.ImportDeclContext(FromDC, true); | |||
8410 | } | |||
8411 | ||||
8412 | Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) { | |||
8413 | if (!FromName) | |||
8414 | return DeclarationName{}; | |||
8415 | ||||
8416 | switch (FromName.getNameKind()) { | |||
8417 | case DeclarationName::Identifier: | |||
8418 | return DeclarationName(Import(FromName.getAsIdentifierInfo())); | |||
8419 | ||||
8420 | case DeclarationName::ObjCZeroArgSelector: | |||
8421 | case DeclarationName::ObjCOneArgSelector: | |||
8422 | case DeclarationName::ObjCMultiArgSelector: | |||
8423 | if (auto ToSelOrErr = Import(FromName.getObjCSelector())) | |||
8424 | return DeclarationName(*ToSelOrErr); | |||
8425 | else | |||
8426 | return ToSelOrErr.takeError(); | |||
8427 | ||||
8428 | case DeclarationName::CXXConstructorName: { | |||
8429 | if (auto ToTyOrErr = Import(FromName.getCXXNameType())) | |||
8430 | return ToContext.DeclarationNames.getCXXConstructorName( | |||
8431 | ToContext.getCanonicalType(*ToTyOrErr)); | |||
8432 | else | |||
8433 | return ToTyOrErr.takeError(); | |||
8434 | } | |||
8435 | ||||
8436 | case DeclarationName::CXXDestructorName: { | |||
8437 | if (auto ToTyOrErr = Import(FromName.getCXXNameType())) | |||
8438 | return ToContext.DeclarationNames.getCXXDestructorName( | |||
8439 | ToContext.getCanonicalType(*ToTyOrErr)); | |||
8440 | else | |||
8441 | return ToTyOrErr.takeError(); | |||
8442 | } | |||
8443 | ||||
8444 | case DeclarationName::CXXDeductionGuideName: { | |||
8445 | if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate())) | |||
8446 | return ToContext.DeclarationNames.getCXXDeductionGuideName( | |||
8447 | cast<TemplateDecl>(*ToTemplateOrErr)); | |||
8448 | else | |||
8449 | return ToTemplateOrErr.takeError(); | |||
8450 | } | |||
8451 | ||||
8452 | case DeclarationName::CXXConversionFunctionName: { | |||
8453 | if (auto ToTyOrErr = Import(FromName.getCXXNameType())) | |||
8454 | return ToContext.DeclarationNames.getCXXConversionFunctionName( | |||
8455 | ToContext.getCanonicalType(*ToTyOrErr)); | |||
8456 | else | |||
8457 | return ToTyOrErr.takeError(); | |||
8458 | } | |||
8459 | ||||
8460 | case DeclarationName::CXXOperatorName: | |||
8461 | return ToContext.DeclarationNames.getCXXOperatorName( | |||
8462 | FromName.getCXXOverloadedOperator()); | |||
8463 | ||||
8464 | case DeclarationName::CXXLiteralOperatorName: | |||
8465 | return ToContext.DeclarationNames.getCXXLiteralOperatorName( | |||
8466 | Import(FromName.getCXXLiteralIdentifier())); | |||
8467 | ||||
8468 | case DeclarationName::CXXUsingDirective: | |||
8469 | // FIXME: STATICS! | |||
8470 | return DeclarationName::getUsingDirectiveName(); | |||
8471 | } | |||
8472 | ||||
8473 | llvm_unreachable("Invalid DeclarationName Kind!")::llvm::llvm_unreachable_internal("Invalid DeclarationName Kind!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 8473); | |||
8474 | } | |||
8475 | ||||
8476 | IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) { | |||
8477 | if (!FromId) | |||
8478 | return nullptr; | |||
8479 | ||||
8480 | IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName()); | |||
8481 | ||||
8482 | if (!ToId->getBuiltinID() && FromId->getBuiltinID()) | |||
8483 | ToId->setBuiltinID(FromId->getBuiltinID()); | |||
8484 | ||||
8485 | return ToId; | |||
8486 | } | |||
8487 | ||||
8488 | Expected<Selector> ASTImporter::Import(Selector FromSel) { | |||
8489 | if (FromSel.isNull()) | |||
8490 | return Selector{}; | |||
8491 | ||||
8492 | SmallVector<IdentifierInfo *, 4> Idents; | |||
8493 | Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0))); | |||
8494 | for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I) | |||
8495 | Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I))); | |||
8496 | return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data()); | |||
8497 | } | |||
8498 | ||||
8499 | DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name, | |||
8500 | DeclContext *DC, | |||
8501 | unsigned IDNS, | |||
8502 | NamedDecl **Decls, | |||
8503 | unsigned NumDecls) { | |||
8504 | return Name; | |||
8505 | } | |||
8506 | ||||
8507 | DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) { | |||
8508 | if (LastDiagFromFrom) | |||
8509 | ToContext.getDiagnostics().notePriorDiagnosticFrom( | |||
8510 | FromContext.getDiagnostics()); | |||
8511 | LastDiagFromFrom = false; | |||
8512 | return ToContext.getDiagnostics().Report(Loc, DiagID); | |||
8513 | } | |||
8514 | ||||
8515 | DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) { | |||
8516 | if (!LastDiagFromFrom) | |||
8517 | FromContext.getDiagnostics().notePriorDiagnosticFrom( | |||
8518 | ToContext.getDiagnostics()); | |||
8519 | LastDiagFromFrom = true; | |||
8520 | return FromContext.getDiagnostics().Report(Loc, DiagID); | |||
8521 | } | |||
8522 | ||||
8523 | void ASTImporter::CompleteDecl (Decl *D) { | |||
8524 | if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) { | |||
8525 | if (!ID->getDefinition()) | |||
8526 | ID->startDefinition(); | |||
8527 | } | |||
8528 | else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) { | |||
8529 | if (!PD->getDefinition()) | |||
8530 | PD->startDefinition(); | |||
8531 | } | |||
8532 | else if (auto *TD = dyn_cast<TagDecl>(D)) { | |||
8533 | if (!TD->getDefinition() && !TD->isBeingDefined()) { | |||
8534 | TD->startDefinition(); | |||
8535 | TD->setCompleteDefinition(true); | |||
8536 | } | |||
8537 | } | |||
8538 | else { | |||
8539 | assert(0 && "CompleteDecl called on a Decl that can't be completed")((0 && "CompleteDecl called on a Decl that can't be completed" ) ? static_cast<void> (0) : __assert_fail ("0 && \"CompleteDecl called on a Decl that can't be completed\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 8539, __PRETTY_FUNCTION__)); | |||
8540 | } | |||
8541 | } | |||
8542 | ||||
8543 | Decl *ASTImporter::MapImported(Decl *From, Decl *To) { | |||
8544 | llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From); | |||
8545 | assert((Pos == ImportedDecls.end() || Pos->second == To) &&(((Pos == ImportedDecls.end() || Pos->second == To) && "Try to import an already imported Decl") ? static_cast<void > (0) : __assert_fail ("(Pos == ImportedDecls.end() || Pos->second == To) && \"Try to import an already imported Decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 8546, __PRETTY_FUNCTION__)) | |||
8546 | "Try to import an already imported Decl")(((Pos == ImportedDecls.end() || Pos->second == To) && "Try to import an already imported Decl") ? static_cast<void > (0) : __assert_fail ("(Pos == ImportedDecls.end() || Pos->second == To) && \"Try to import an already imported Decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp" , 8546, __PRETTY_FUNCTION__)); | |||
8547 | if (Pos != ImportedDecls.end()) | |||
8548 | return Pos->second; | |||
8549 | ImportedDecls[From] = To; | |||
8550 | // This mapping should be maintained only in this function. Therefore do not | |||
8551 | // check for additional consistency. | |||
8552 | ImportedFromDecls[To] = From; | |||
8553 | return To; | |||
8554 | } | |||
8555 | ||||
8556 | bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To, | |||
8557 | bool Complain) { | |||
8558 | llvm::DenseMap<const Type *, const Type *>::iterator Pos = | |||
8559 | ImportedTypes.find(From.getTypePtr()); | |||
8560 | if (Pos != ImportedTypes.end()) { | |||
8561 | if (ExpectedType ToFromOrErr = Import(From)) { | |||
8562 | if (ToContext.hasSameType(*ToFromOrErr, To)) | |||
8563 | return true; | |||
8564 | } else { | |||
8565 | llvm::consumeError(ToFromOrErr.takeError()); | |||
8566 | } | |||
8567 | } | |||
8568 | ||||
8569 | StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls, | |||
8570 | getStructuralEquivalenceKind(*this), false, | |||
8571 | Complain); | |||
8572 | return Ctx.IsEquivalent(From, To); | |||
8573 | } |
1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file defines an API used to report recoverable errors. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #ifndef LLVM_SUPPORT_ERROR_H | |||
14 | #define LLVM_SUPPORT_ERROR_H | |||
15 | ||||
16 | #include "llvm-c/Error.h" | |||
17 | #include "llvm/ADT/STLExtras.h" | |||
18 | #include "llvm/ADT/SmallVector.h" | |||
19 | #include "llvm/ADT/StringExtras.h" | |||
20 | #include "llvm/ADT/Twine.h" | |||
21 | #include "llvm/Config/abi-breaking.h" | |||
22 | #include "llvm/Support/AlignOf.h" | |||
23 | #include "llvm/Support/Compiler.h" | |||
24 | #include "llvm/Support/Debug.h" | |||
25 | #include "llvm/Support/ErrorHandling.h" | |||
26 | #include "llvm/Support/ErrorOr.h" | |||
27 | #include "llvm/Support/Format.h" | |||
28 | #include "llvm/Support/raw_ostream.h" | |||
29 | #include <algorithm> | |||
30 | #include <cassert> | |||
31 | #include <cstdint> | |||
32 | #include <cstdlib> | |||
33 | #include <functional> | |||
34 | #include <memory> | |||
35 | #include <new> | |||
36 | #include <string> | |||
37 | #include <system_error> | |||
38 | #include <type_traits> | |||
39 | #include <utility> | |||
40 | #include <vector> | |||
41 | ||||
42 | namespace llvm { | |||
43 | ||||
44 | class ErrorSuccess; | |||
45 | ||||
46 | /// Base class for error info classes. Do not extend this directly: Extend | |||
47 | /// the ErrorInfo template subclass instead. | |||
48 | class ErrorInfoBase { | |||
49 | public: | |||
50 | virtual ~ErrorInfoBase() = default; | |||
51 | ||||
52 | /// Print an error message to an output stream. | |||
53 | virtual void log(raw_ostream &OS) const = 0; | |||
54 | ||||
55 | /// Return the error message as a string. | |||
56 | virtual std::string message() const { | |||
57 | std::string Msg; | |||
58 | raw_string_ostream OS(Msg); | |||
59 | log(OS); | |||
60 | return OS.str(); | |||
61 | } | |||
62 | ||||
63 | /// Convert this error to a std::error_code. | |||
64 | /// | |||
65 | /// This is a temporary crutch to enable interaction with code still | |||
66 | /// using std::error_code. It will be removed in the future. | |||
67 | virtual std::error_code convertToErrorCode() const = 0; | |||
68 | ||||
69 | // Returns the class ID for this type. | |||
70 | static const void *classID() { return &ID; } | |||
71 | ||||
72 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. | |||
73 | virtual const void *dynamicClassID() const = 0; | |||
74 | ||||
75 | // Check whether this instance is a subclass of the class identified by | |||
76 | // ClassID. | |||
77 | virtual bool isA(const void *const ClassID) const { | |||
78 | return ClassID == classID(); | |||
79 | } | |||
80 | ||||
81 | // Check whether this instance is a subclass of ErrorInfoT. | |||
82 | template <typename ErrorInfoT> bool isA() const { | |||
83 | return isA(ErrorInfoT::classID()); | |||
84 | } | |||
85 | ||||
86 | private: | |||
87 | virtual void anchor(); | |||
88 | ||||
89 | static char ID; | |||
90 | }; | |||
91 | ||||
92 | /// Lightweight error class with error context and mandatory checking. | |||
93 | /// | |||
94 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states | |||
95 | /// are represented by setting the pointer to a ErrorInfoBase subclass | |||
96 | /// instance containing information describing the failure. Success is | |||
97 | /// represented by a null pointer value. | |||
98 | /// | |||
99 | /// Instances of Error also contains a 'Checked' flag, which must be set | |||
100 | /// before the destructor is called, otherwise the destructor will trigger a | |||
101 | /// runtime error. This enforces at runtime the requirement that all Error | |||
102 | /// instances be checked or returned to the caller. | |||
103 | /// | |||
104 | /// There are two ways to set the checked flag, depending on what state the | |||
105 | /// Error instance is in. For Error instances indicating success, it | |||
106 | /// is sufficient to invoke the boolean conversion operator. E.g.: | |||
107 | /// | |||
108 | /// @code{.cpp} | |||
109 | /// Error foo(<...>); | |||
110 | /// | |||
111 | /// if (auto E = foo(<...>)) | |||
112 | /// return E; // <- Return E if it is in the error state. | |||
113 | /// // We have verified that E was in the success state. It can now be safely | |||
114 | /// // destroyed. | |||
115 | /// @endcode | |||
116 | /// | |||
117 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' | |||
118 | /// without testing the return value will raise a runtime error, even if foo | |||
119 | /// returns success. | |||
120 | /// | |||
121 | /// For Error instances representing failure, you must use either the | |||
122 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: | |||
123 | /// | |||
124 | /// @code{.cpp} | |||
125 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { | |||
126 | /// // Custom error info. | |||
127 | /// }; | |||
128 | /// | |||
129 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } | |||
130 | /// | |||
131 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. | |||
132 | /// auto NewE = | |||
133 | /// handleErrors(E, | |||
134 | /// [](const MyErrorInfo &M) { | |||
135 | /// // Deal with the error. | |||
136 | /// }, | |||
137 | /// [](std::unique_ptr<OtherError> M) -> Error { | |||
138 | /// if (canHandle(*M)) { | |||
139 | /// // handle error. | |||
140 | /// return Error::success(); | |||
141 | /// } | |||
142 | /// // Couldn't handle this error instance. Pass it up the stack. | |||
143 | /// return Error(std::move(M)); | |||
144 | /// ); | |||
145 | /// // Note - we must check or return NewE in case any of the handlers | |||
146 | /// // returned a new error. | |||
147 | /// @endcode | |||
148 | /// | |||
149 | /// The handleAllErrors function is identical to handleErrors, except | |||
150 | /// that it has a void return type, and requires all errors to be handled and | |||
151 | /// no new errors be returned. It prevents errors (assuming they can all be | |||
152 | /// handled) from having to be bubbled all the way to the top-level. | |||
153 | /// | |||
154 | /// *All* Error instances must be checked before destruction, even if | |||
155 | /// they're moved-assigned or constructed from Success values that have already | |||
156 | /// been checked. This enforces checking through all levels of the call stack. | |||
157 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { | |||
158 | // Both ErrorList and FileError need to be able to yank ErrorInfoBase | |||
159 | // pointers out of this class to add to the error list. | |||
160 | friend class ErrorList; | |||
161 | friend class FileError; | |||
162 | ||||
163 | // handleErrors needs to be able to set the Checked flag. | |||
164 | template <typename... HandlerTs> | |||
165 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); | |||
166 | ||||
167 | // Expected<T> needs to be able to steal the payload when constructed from an | |||
168 | // error. | |||
169 | template <typename T> friend class Expected; | |||
170 | ||||
171 | // wrap needs to be able to steal the payload. | |||
172 | friend LLVMErrorRef wrap(Error); | |||
173 | ||||
174 | protected: | |||
175 | /// Create a success value. Prefer using 'Error::success()' for readability | |||
176 | Error() { | |||
177 | setPtr(nullptr); | |||
178 | setChecked(false); | |||
179 | } | |||
180 | ||||
181 | public: | |||
182 | /// Create a success value. | |||
183 | static ErrorSuccess success(); | |||
184 | ||||
185 | // Errors are not copy-constructable. | |||
186 | Error(const Error &Other) = delete; | |||
187 | ||||
188 | /// Move-construct an error value. The newly constructed error is considered | |||
189 | /// unchecked, even if the source error had been checked. The original error | |||
190 | /// becomes a checked Success value, regardless of its original state. | |||
191 | Error(Error &&Other) { | |||
192 | setChecked(true); | |||
193 | *this = std::move(Other); | |||
194 | } | |||
195 | ||||
196 | /// Create an error value. Prefer using the 'make_error' function, but | |||
197 | /// this constructor can be useful when "re-throwing" errors from handlers. | |||
198 | Error(std::unique_ptr<ErrorInfoBase> Payload) { | |||
199 | setPtr(Payload.release()); | |||
200 | setChecked(false); | |||
| ||||
201 | } | |||
202 | ||||
203 | // Errors are not copy-assignable. | |||
204 | Error &operator=(const Error &Other) = delete; | |||
205 | ||||
206 | /// Move-assign an error value. The current error must represent success, you | |||
207 | /// you cannot overwrite an unhandled error. The current error is then | |||
208 | /// considered unchecked. The source error becomes a checked success value, | |||
209 | /// regardless of its original state. | |||
210 | Error &operator=(Error &&Other) { | |||
211 | // Don't allow overwriting of unchecked values. | |||
212 | assertIsChecked(); | |||
213 | setPtr(Other.getPtr()); | |||
214 | ||||
215 | // This Error is unchecked, even if the source error was checked. | |||
216 | setChecked(false); | |||
217 | ||||
218 | // Null out Other's payload and set its checked bit. | |||
219 | Other.setPtr(nullptr); | |||
220 | Other.setChecked(true); | |||
221 | ||||
222 | return *this; | |||
223 | } | |||
224 | ||||
225 | /// Destroy a Error. Fails with a call to abort() if the error is | |||
226 | /// unchecked. | |||
227 | ~Error() { | |||
228 | assertIsChecked(); | |||
229 | delete getPtr(); | |||
230 | } | |||
231 | ||||
232 | /// Bool conversion. Returns true if this Error is in a failure state, | |||
233 | /// and false if it is in an accept state. If the error is in a Success state | |||
234 | /// it will be considered checked. | |||
235 | explicit operator bool() { | |||
236 | setChecked(getPtr() == nullptr); | |||
237 | return getPtr() != nullptr; | |||
238 | } | |||
239 | ||||
240 | /// Check whether one error is a subclass of another. | |||
241 | template <typename ErrT> bool isA() const { | |||
242 | return getPtr() && getPtr()->isA(ErrT::classID()); | |||
243 | } | |||
244 | ||||
245 | /// Returns the dynamic class id of this error, or null if this is a success | |||
246 | /// value. | |||
247 | const void* dynamicClassID() const { | |||
248 | if (!getPtr()) | |||
249 | return nullptr; | |||
250 | return getPtr()->dynamicClassID(); | |||
251 | } | |||
252 | ||||
253 | private: | |||
254 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
255 | // assertIsChecked() happens very frequently, but under normal circumstances | |||
256 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch | |||
257 | // of debug prints can cause the function to be too large for inlining. So | |||
258 | // it's important that we define this function out of line so that it can't be | |||
259 | // inlined. | |||
260 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) | |||
261 | void fatalUncheckedError() const; | |||
262 | #endif | |||
263 | ||||
264 | void assertIsChecked() { | |||
265 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
266 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) | |||
267 | fatalUncheckedError(); | |||
268 | #endif | |||
269 | } | |||
270 | ||||
271 | ErrorInfoBase *getPtr() const { | |||
272 | return reinterpret_cast<ErrorInfoBase*>( | |||
273 | reinterpret_cast<uintptr_t>(Payload) & | |||
274 | ~static_cast<uintptr_t>(0x1)); | |||
275 | } | |||
276 | ||||
277 | void setPtr(ErrorInfoBase *EI) { | |||
278 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
279 | Payload = reinterpret_cast<ErrorInfoBase*>( | |||
280 | (reinterpret_cast<uintptr_t>(EI) & | |||
281 | ~static_cast<uintptr_t>(0x1)) | | |||
282 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); | |||
283 | #else | |||
284 | Payload = EI; | |||
285 | #endif | |||
286 | } | |||
287 | ||||
288 | bool getChecked() const { | |||
289 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
290 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; | |||
291 | #else | |||
292 | return true; | |||
293 | #endif | |||
294 | } | |||
295 | ||||
296 | void setChecked(bool V) { | |||
297 | Payload = reinterpret_cast<ErrorInfoBase*>( | |||
298 | (reinterpret_cast<uintptr_t>(Payload) & | |||
299 | ~static_cast<uintptr_t>(0x1)) | | |||
300 | (V ? 0 : 1)); | |||
301 | } | |||
302 | ||||
303 | std::unique_ptr<ErrorInfoBase> takePayload() { | |||
304 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); | |||
305 | setPtr(nullptr); | |||
306 | setChecked(true); | |||
307 | return Tmp; | |||
308 | } | |||
309 | ||||
310 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { | |||
311 | if (auto P = E.getPtr()) | |||
312 | P->log(OS); | |||
313 | else | |||
314 | OS << "success"; | |||
315 | return OS; | |||
316 | } | |||
317 | ||||
318 | ErrorInfoBase *Payload = nullptr; | |||
319 | }; | |||
320 | ||||
321 | /// Subclass of Error for the sole purpose of identifying the success path in | |||
322 | /// the type system. This allows to catch invalid conversion to Expected<T> at | |||
323 | /// compile time. | |||
324 | class ErrorSuccess final : public Error {}; | |||
325 | ||||
326 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } | |||
327 | ||||
328 | /// Make a Error instance representing failure using the given error info | |||
329 | /// type. | |||
330 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { | |||
331 | return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); | |||
332 | } | |||
333 | ||||
334 | /// Base class for user error types. Users should declare their error types | |||
335 | /// like: | |||
336 | /// | |||
337 | /// class MyError : public ErrorInfo<MyError> { | |||
338 | /// .... | |||
339 | /// }; | |||
340 | /// | |||
341 | /// This class provides an implementation of the ErrorInfoBase::kind | |||
342 | /// method, which is used by the Error RTTI system. | |||
343 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> | |||
344 | class ErrorInfo : public ParentErrT { | |||
345 | public: | |||
346 | using ParentErrT::ParentErrT; // inherit constructors | |||
347 | ||||
348 | static const void *classID() { return &ThisErrT::ID; } | |||
349 | ||||
350 | const void *dynamicClassID() const override { return &ThisErrT::ID; } | |||
351 | ||||
352 | bool isA(const void *const ClassID) const override { | |||
353 | return ClassID == classID() || ParentErrT::isA(ClassID); | |||
354 | } | |||
355 | }; | |||
356 | ||||
357 | /// Special ErrorInfo subclass representing a list of ErrorInfos. | |||
358 | /// Instances of this class are constructed by joinError. | |||
359 | class ErrorList final : public ErrorInfo<ErrorList> { | |||
360 | // handleErrors needs to be able to iterate the payload list of an | |||
361 | // ErrorList. | |||
362 | template <typename... HandlerTs> | |||
363 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); | |||
364 | ||||
365 | // joinErrors is implemented in terms of join. | |||
366 | friend Error joinErrors(Error, Error); | |||
367 | ||||
368 | public: | |||
369 | void log(raw_ostream &OS) const override { | |||
370 | OS << "Multiple errors:\n"; | |||
371 | for (auto &ErrPayload : Payloads) { | |||
372 | ErrPayload->log(OS); | |||
373 | OS << "\n"; | |||
374 | } | |||
375 | } | |||
376 | ||||
377 | std::error_code convertToErrorCode() const override; | |||
378 | ||||
379 | // Used by ErrorInfo::classID. | |||
380 | static char ID; | |||
381 | ||||
382 | private: | |||
383 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, | |||
384 | std::unique_ptr<ErrorInfoBase> Payload2) { | |||
385 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)) | |||
386 | "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)); | |||
387 | Payloads.push_back(std::move(Payload1)); | |||
388 | Payloads.push_back(std::move(Payload2)); | |||
389 | } | |||
390 | ||||
391 | static Error join(Error E1, Error E2) { | |||
392 | if (!E1) | |||
393 | return E2; | |||
394 | if (!E2) | |||
395 | return E1; | |||
396 | if (E1.isA<ErrorList>()) { | |||
397 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); | |||
398 | if (E2.isA<ErrorList>()) { | |||
399 | auto E2Payload = E2.takePayload(); | |||
400 | auto &E2List = static_cast<ErrorList &>(*E2Payload); | |||
401 | for (auto &Payload : E2List.Payloads) | |||
402 | E1List.Payloads.push_back(std::move(Payload)); | |||
403 | } else | |||
404 | E1List.Payloads.push_back(E2.takePayload()); | |||
405 | ||||
406 | return E1; | |||
407 | } | |||
408 | if (E2.isA<ErrorList>()) { | |||
409 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); | |||
410 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); | |||
411 | return E2; | |||
412 | } | |||
413 | return Error(std::unique_ptr<ErrorList>( | |||
414 | new ErrorList(E1.takePayload(), E2.takePayload()))); | |||
415 | } | |||
416 | ||||
417 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; | |||
418 | }; | |||
419 | ||||
420 | /// Concatenate errors. The resulting Error is unchecked, and contains the | |||
421 | /// ErrorInfo(s), if any, contained in E1, followed by the | |||
422 | /// ErrorInfo(s), if any, contained in E2. | |||
423 | inline Error joinErrors(Error E1, Error E2) { | |||
424 | return ErrorList::join(std::move(E1), std::move(E2)); | |||
425 | } | |||
426 | ||||
427 | /// Tagged union holding either a T or a Error. | |||
428 | /// | |||
429 | /// This class parallels ErrorOr, but replaces error_code with Error. Since | |||
430 | /// Error cannot be copied, this class replaces getError() with | |||
431 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the | |||
432 | /// error class type. | |||
433 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { | |||
434 | template <class T1> friend class ExpectedAsOutParameter; | |||
435 | template <class OtherT> friend class Expected; | |||
436 | ||||
437 | static const bool isRef = std::is_reference<T>::value; | |||
438 | ||||
439 | using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>; | |||
440 | ||||
441 | using error_type = std::unique_ptr<ErrorInfoBase>; | |||
442 | ||||
443 | public: | |||
444 | using storage_type = typename std::conditional<isRef, wrap, T>::type; | |||
445 | using value_type = T; | |||
446 | ||||
447 | private: | |||
448 | using reference = typename std::remove_reference<T>::type &; | |||
449 | using const_reference = const typename std::remove_reference<T>::type &; | |||
450 | using pointer = typename std::remove_reference<T>::type *; | |||
451 | using const_pointer = const typename std::remove_reference<T>::type *; | |||
452 | ||||
453 | public: | |||
454 | /// Create an Expected<T> error value from the given Error. | |||
455 | Expected(Error Err) | |||
456 | : HasError(true) | |||
457 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
458 | // Expected is unchecked upon construction in Debug builds. | |||
459 | , Unchecked(true) | |||
460 | #endif | |||
461 | { | |||
462 | assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value." ) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 462, __PRETTY_FUNCTION__)); | |||
463 | new (getErrorStorage()) error_type(Err.takePayload()); | |||
464 | } | |||
465 | ||||
466 | /// Forbid to convert from Error::success() implicitly, this avoids having | |||
467 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise | |||
468 | /// but triggers the assertion above. | |||
469 | Expected(ErrorSuccess) = delete; | |||
470 | ||||
471 | /// Create an Expected<T> success value from the given OtherT value, which | |||
472 | /// must be convertible to T. | |||
473 | template <typename OtherT> | |||
474 | Expected(OtherT &&Val, | |||
475 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type | |||
476 | * = nullptr) | |||
477 | : HasError(false) | |||
478 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
479 | // Expected is unchecked upon construction in Debug builds. | |||
480 | , Unchecked(true) | |||
481 | #endif | |||
482 | { | |||
483 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); | |||
484 | } | |||
485 | ||||
486 | /// Move construct an Expected<T> value. | |||
487 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } | |||
488 | ||||
489 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT | |||
490 | /// must be convertible to T. | |||
491 | template <class OtherT> | |||
492 | Expected(Expected<OtherT> &&Other, | |||
493 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type | |||
494 | * = nullptr) { | |||
495 | moveConstruct(std::move(Other)); | |||
496 | } | |||
497 | ||||
498 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT | |||
499 | /// isn't convertible to T. | |||
500 | template <class OtherT> | |||
501 | explicit Expected( | |||
502 | Expected<OtherT> &&Other, | |||
503 | typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = | |||
504 | nullptr) { | |||
505 | moveConstruct(std::move(Other)); | |||
506 | } | |||
507 | ||||
508 | /// Move-assign from another Expected<T>. | |||
509 | Expected &operator=(Expected &&Other) { | |||
510 | moveAssign(std::move(Other)); | |||
511 | return *this; | |||
512 | } | |||
513 | ||||
514 | /// Destroy an Expected<T>. | |||
515 | ~Expected() { | |||
516 | assertIsChecked(); | |||
517 | if (!HasError) | |||
518 | getStorage()->~storage_type(); | |||
519 | else | |||
520 | getErrorStorage()->~error_type(); | |||
521 | } | |||
522 | ||||
523 | /// Return false if there is an error. | |||
524 | explicit operator bool() { | |||
525 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
526 | Unchecked = HasError; | |||
527 | #endif | |||
528 | return !HasError; | |||
529 | } | |||
530 | ||||
531 | /// Returns a reference to the stored T value. | |||
532 | reference get() { | |||
533 | assertIsChecked(); | |||
534 | return *getStorage(); | |||
535 | } | |||
536 | ||||
537 | /// Returns a const reference to the stored T value. | |||
538 | const_reference get() const { | |||
539 | assertIsChecked(); | |||
540 | return const_cast<Expected<T> *>(this)->get(); | |||
541 | } | |||
542 | ||||
543 | /// Check that this Expected<T> is an error of type ErrT. | |||
544 | template <typename ErrT> bool errorIsA() const { | |||
545 | return HasError && (*getErrorStorage())->template isA<ErrT>(); | |||
546 | } | |||
547 | ||||
548 | /// Take ownership of the stored error. | |||
549 | /// After calling this the Expected<T> is in an indeterminate state that can | |||
550 | /// only be safely destructed. No further calls (beside the destructor) should | |||
551 | /// be made on the Expected<T> vaule. | |||
552 | Error takeError() { | |||
553 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
554 | Unchecked = false; | |||
555 | #endif | |||
556 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); | |||
557 | } | |||
558 | ||||
559 | /// Returns a pointer to the stored T value. | |||
560 | pointer operator->() { | |||
561 | assertIsChecked(); | |||
562 | return toPointer(getStorage()); | |||
563 | } | |||
564 | ||||
565 | /// Returns a const pointer to the stored T value. | |||
566 | const_pointer operator->() const { | |||
567 | assertIsChecked(); | |||
568 | return toPointer(getStorage()); | |||
569 | } | |||
570 | ||||
571 | /// Returns a reference to the stored T value. | |||
572 | reference operator*() { | |||
573 | assertIsChecked(); | |||
574 | return *getStorage(); | |||
575 | } | |||
576 | ||||
577 | /// Returns a const reference to the stored T value. | |||
578 | const_reference operator*() const { | |||
579 | assertIsChecked(); | |||
580 | return *getStorage(); | |||
581 | } | |||
582 | ||||
583 | private: | |||
584 | template <class T1> | |||
585 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { | |||
586 | return &a == &b; | |||
587 | } | |||
588 | ||||
589 | template <class T1, class T2> | |||
590 | static bool compareThisIfSameType(const T1 &a, const T2 &b) { | |||
591 | return false; | |||
592 | } | |||
593 | ||||
594 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { | |||
595 | HasError = Other.HasError; | |||
596 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
597 | Unchecked = true; | |||
598 | Other.Unchecked = false; | |||
599 | #endif | |||
600 | ||||
601 | if (!HasError) | |||
602 | new (getStorage()) storage_type(std::move(*Other.getStorage())); | |||
603 | else | |||
604 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); | |||
605 | } | |||
606 | ||||
607 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { | |||
608 | assertIsChecked(); | |||
609 | ||||
610 | if (compareThisIfSameType(*this, Other)) | |||
611 | return; | |||
612 | ||||
613 | this->~Expected(); | |||
614 | new (this) Expected(std::move(Other)); | |||
615 | } | |||
616 | ||||
617 | pointer toPointer(pointer Val) { return Val; } | |||
618 | ||||
619 | const_pointer toPointer(const_pointer Val) const { return Val; } | |||
620 | ||||
621 | pointer toPointer(wrap *Val) { return &Val->get(); } | |||
622 | ||||
623 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } | |||
624 | ||||
625 | storage_type *getStorage() { | |||
626 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 626, __PRETTY_FUNCTION__)); | |||
627 | return reinterpret_cast<storage_type *>(TStorage.buffer); | |||
628 | } | |||
629 | ||||
630 | const storage_type *getStorage() const { | |||
631 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 631, __PRETTY_FUNCTION__)); | |||
632 | return reinterpret_cast<const storage_type *>(TStorage.buffer); | |||
633 | } | |||
634 | ||||
635 | error_type *getErrorStorage() { | |||
636 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 636, __PRETTY_FUNCTION__)); | |||
637 | return reinterpret_cast<error_type *>(ErrorStorage.buffer); | |||
638 | } | |||
639 | ||||
640 | const error_type *getErrorStorage() const { | |||
641 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 641, __PRETTY_FUNCTION__)); | |||
642 | return reinterpret_cast<const error_type *>(ErrorStorage.buffer); | |||
643 | } | |||
644 | ||||
645 | // Used by ExpectedAsOutParameter to reset the checked flag. | |||
646 | void setUnchecked() { | |||
647 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
648 | Unchecked = true; | |||
649 | #endif | |||
650 | } | |||
651 | ||||
652 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
653 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) | |||
654 | LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) | |||
655 | void fatalUncheckedExpected() const { | |||
656 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; | |||
657 | if (HasError) { | |||
658 | dbgs() << "Unchecked Expected<T> contained error:\n"; | |||
659 | (*getErrorStorage())->log(dbgs()); | |||
660 | } else | |||
661 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " | |||
662 | "values in success mode must still be checked prior to being " | |||
663 | "destroyed).\n"; | |||
664 | abort(); | |||
665 | } | |||
666 | #endif | |||
667 | ||||
668 | void assertIsChecked() { | |||
669 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
670 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) | |||
671 | fatalUncheckedExpected(); | |||
672 | #endif | |||
673 | } | |||
674 | ||||
675 | union { | |||
676 | AlignedCharArrayUnion<storage_type> TStorage; | |||
677 | AlignedCharArrayUnion<error_type> ErrorStorage; | |||
678 | }; | |||
679 | bool HasError : 1; | |||
680 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
681 | bool Unchecked : 1; | |||
682 | #endif | |||
683 | }; | |||
684 | ||||
685 | /// Report a serious error, calling any installed error handler. See | |||
686 | /// ErrorHandling.h. | |||
687 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err, | |||
688 | bool gen_crash_diag = true); | |||
689 | ||||
690 | /// Report a fatal error if Err is a failure value. | |||
691 | /// | |||
692 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
693 | /// is known that the Error will always be a success value. E.g. | |||
694 | /// | |||
695 | /// @code{.cpp} | |||
696 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
697 | /// // true. If DoFallibleOperation is false then foo always returns | |||
698 | /// // Error::success(). | |||
699 | /// Error foo(bool DoFallibleOperation); | |||
700 | /// | |||
701 | /// cantFail(foo(false)); | |||
702 | /// @endcode | |||
703 | inline void cantFail(Error Err, const char *Msg = nullptr) { | |||
704 | if (Err) { | |||
705 | if (!Msg) | |||
706 | Msg = "Failure value returned from cantFail wrapped call"; | |||
707 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 707); | |||
708 | } | |||
709 | } | |||
710 | ||||
711 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and | |||
712 | /// returns the contained value. | |||
713 | /// | |||
714 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
715 | /// is known that the Error will always be a success value. E.g. | |||
716 | /// | |||
717 | /// @code{.cpp} | |||
718 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
719 | /// // true. If DoFallibleOperation is false then foo always returns an int. | |||
720 | /// Expected<int> foo(bool DoFallibleOperation); | |||
721 | /// | |||
722 | /// int X = cantFail(foo(false)); | |||
723 | /// @endcode | |||
724 | template <typename T> | |||
725 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { | |||
726 | if (ValOrErr) | |||
727 | return std::move(*ValOrErr); | |||
728 | else { | |||
729 | if (!Msg) | |||
730 | Msg = "Failure value returned from cantFail wrapped call"; | |||
731 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 731); | |||
732 | } | |||
733 | } | |||
734 | ||||
735 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and | |||
736 | /// returns the contained reference. | |||
737 | /// | |||
738 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
739 | /// is known that the Error will always be a success value. E.g. | |||
740 | /// | |||
741 | /// @code{.cpp} | |||
742 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
743 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. | |||
744 | /// Expected<Bar&> foo(bool DoFallibleOperation); | |||
745 | /// | |||
746 | /// Bar &X = cantFail(foo(false)); | |||
747 | /// @endcode | |||
748 | template <typename T> | |||
749 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { | |||
750 | if (ValOrErr) | |||
751 | return *ValOrErr; | |||
752 | else { | |||
753 | if (!Msg) | |||
754 | Msg = "Failure value returned from cantFail wrapped call"; | |||
755 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 755); | |||
756 | } | |||
757 | } | |||
758 | ||||
759 | /// Helper for testing applicability of, and applying, handlers for | |||
760 | /// ErrorInfo types. | |||
761 | template <typename HandlerT> | |||
762 | class ErrorHandlerTraits | |||
763 | : public ErrorHandlerTraits<decltype( | |||
764 | &std::remove_reference<HandlerT>::type::operator())> {}; | |||
765 | ||||
766 | // Specialization functions of the form 'Error (const ErrT&)'. | |||
767 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { | |||
768 | public: | |||
769 | static bool appliesTo(const ErrorInfoBase &E) { | |||
770 | return E.template isA<ErrT>(); | |||
771 | } | |||
772 | ||||
773 | template <typename HandlerT> | |||
774 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
775 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 775, __PRETTY_FUNCTION__)); | |||
776 | return H(static_cast<ErrT &>(*E)); | |||
777 | } | |||
778 | }; | |||
779 | ||||
780 | // Specialization functions of the form 'void (const ErrT&)'. | |||
781 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { | |||
782 | public: | |||
783 | static bool appliesTo(const ErrorInfoBase &E) { | |||
784 | return E.template isA<ErrT>(); | |||
785 | } | |||
786 | ||||
787 | template <typename HandlerT> | |||
788 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
789 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 789, __PRETTY_FUNCTION__)); | |||
790 | H(static_cast<ErrT &>(*E)); | |||
791 | return Error::success(); | |||
792 | } | |||
793 | }; | |||
794 | ||||
795 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. | |||
796 | template <typename ErrT> | |||
797 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { | |||
798 | public: | |||
799 | static bool appliesTo(const ErrorInfoBase &E) { | |||
800 | return E.template isA<ErrT>(); | |||
801 | } | |||
802 | ||||
803 | template <typename HandlerT> | |||
804 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
805 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 805, __PRETTY_FUNCTION__)); | |||
806 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); | |||
807 | return H(std::move(SubE)); | |||
808 | } | |||
809 | }; | |||
810 | ||||
811 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. | |||
812 | template <typename ErrT> | |||
813 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { | |||
814 | public: | |||
815 | static bool appliesTo(const ErrorInfoBase &E) { | |||
816 | return E.template isA<ErrT>(); | |||
817 | } | |||
818 | ||||
819 | template <typename HandlerT> | |||
820 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
821 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 821, __PRETTY_FUNCTION__)); | |||
822 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); | |||
823 | H(std::move(SubE)); | |||
824 | return Error::success(); | |||
825 | } | |||
826 | }; | |||
827 | ||||
828 | // Specialization for member functions of the form 'RetT (const ErrT&)'. | |||
829 | template <typename C, typename RetT, typename ErrT> | |||
830 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> | |||
831 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
832 | ||||
833 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. | |||
834 | template <typename C, typename RetT, typename ErrT> | |||
835 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> | |||
836 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
837 | ||||
838 | // Specialization for member functions of the form 'RetT (const ErrT&)'. | |||
839 | template <typename C, typename RetT, typename ErrT> | |||
840 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> | |||
841 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
842 | ||||
843 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. | |||
844 | template <typename C, typename RetT, typename ErrT> | |||
845 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> | |||
846 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
847 | ||||
848 | /// Specialization for member functions of the form | |||
849 | /// 'RetT (std::unique_ptr<ErrT>)'. | |||
850 | template <typename C, typename RetT, typename ErrT> | |||
851 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> | |||
852 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; | |||
853 | ||||
854 | /// Specialization for member functions of the form | |||
855 | /// 'RetT (std::unique_ptr<ErrT>) const'. | |||
856 | template <typename C, typename RetT, typename ErrT> | |||
857 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> | |||
858 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; | |||
859 | ||||
860 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { | |||
861 | return Error(std::move(Payload)); | |||
862 | } | |||
863 | ||||
864 | template <typename HandlerT, typename... HandlerTs> | |||
865 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, | |||
866 | HandlerT &&Handler, HandlerTs &&... Handlers) { | |||
867 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) | |||
868 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), | |||
869 | std::move(Payload)); | |||
870 | return handleErrorImpl(std::move(Payload), | |||
871 | std::forward<HandlerTs>(Handlers)...); | |||
872 | } | |||
873 | ||||
874 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any | |||
875 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and | |||
876 | /// returned. | |||
877 | /// Because this function returns an error, its result must also be checked | |||
878 | /// or returned. If you intend to handle all errors use handleAllErrors | |||
879 | /// (which returns void, and will abort() on unhandled errors) instead. | |||
880 | template <typename... HandlerTs> | |||
881 | Error handleErrors(Error E, HandlerTs &&... Hs) { | |||
882 | if (!E) | |||
883 | return Error::success(); | |||
884 | ||||
885 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); | |||
886 | ||||
887 | if (Payload->isA<ErrorList>()) { | |||
888 | ErrorList &List = static_cast<ErrorList &>(*Payload); | |||
889 | Error R; | |||
890 | for (auto &P : List.Payloads) | |||
891 | R = ErrorList::join( | |||
892 | std::move(R), | |||
893 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); | |||
894 | return R; | |||
895 | } | |||
896 | ||||
897 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); | |||
898 | } | |||
899 | ||||
900 | /// Behaves the same as handleErrors, except that by contract all errors | |||
901 | /// *must* be handled by the given handlers (i.e. there must be no remaining | |||
902 | /// errors after running the handlers, or llvm_unreachable is called). | |||
903 | template <typename... HandlerTs> | |||
904 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { | |||
905 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); | |||
906 | } | |||
907 | ||||
908 | /// Check that E is a non-error, then drop it. | |||
909 | /// If E is an error, llvm_unreachable will be called. | |||
910 | inline void handleAllErrors(Error E) { | |||
911 | cantFail(std::move(E)); | |||
912 | } | |||
913 | ||||
914 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. | |||
915 | /// | |||
916 | /// If the incoming value is a success value it is returned unmodified. If it | |||
917 | /// is a failure value then it the contained error is passed to handleErrors. | |||
918 | /// If handleErrors is able to handle the error then the RecoveryPath functor | |||
919 | /// is called to supply the final result. If handleErrors is not able to | |||
920 | /// handle all errors then the unhandled errors are returned. | |||
921 | /// | |||
922 | /// This utility enables the follow pattern: | |||
923 | /// | |||
924 | /// @code{.cpp} | |||
925 | /// enum FooStrategy { Aggressive, Conservative }; | |||
926 | /// Expected<Foo> foo(FooStrategy S); | |||
927 | /// | |||
928 | /// auto ResultOrErr = | |||
929 | /// handleExpected( | |||
930 | /// foo(Aggressive), | |||
931 | /// []() { return foo(Conservative); }, | |||
932 | /// [](AggressiveStrategyError&) { | |||
933 | /// // Implicitly conusme this - we'll recover by using a conservative | |||
934 | /// // strategy. | |||
935 | /// }); | |||
936 | /// | |||
937 | /// @endcode | |||
938 | template <typename T, typename RecoveryFtor, typename... HandlerTs> | |||
939 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, | |||
940 | HandlerTs &&... Handlers) { | |||
941 | if (ValOrErr) | |||
942 | return ValOrErr; | |||
943 | ||||
944 | if (auto Err = handleErrors(ValOrErr.takeError(), | |||
945 | std::forward<HandlerTs>(Handlers)...)) | |||
946 | return std::move(Err); | |||
947 | ||||
948 | return RecoveryPath(); | |||
949 | } | |||
950 | ||||
951 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner | |||
952 | /// will be printed before the first one is logged. A newline will be printed | |||
953 | /// after each error. | |||
954 | /// | |||
955 | /// This function is compatible with the helpers from Support/WithColor.h. You | |||
956 | /// can pass any of them as the OS. Please consider using them instead of | |||
957 | /// including 'error: ' in the ErrorBanner. | |||
958 | /// | |||
959 | /// This is useful in the base level of your program to allow clean termination | |||
960 | /// (allowing clean deallocation of resources, etc.), while reporting error | |||
961 | /// information to the user. | |||
962 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); | |||
963 | ||||
964 | /// Write all error messages (if any) in E to a string. The newline character | |||
965 | /// is used to separate error messages. | |||
966 | inline std::string toString(Error E) { | |||
967 | SmallVector<std::string, 2> Errors; | |||
968 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { | |||
969 | Errors.push_back(EI.message()); | |||
970 | }); | |||
971 | return join(Errors.begin(), Errors.end(), "\n"); | |||
972 | } | |||
973 | ||||
974 | /// Consume a Error without doing anything. This method should be used | |||
975 | /// only where an error can be considered a reasonable and expected return | |||
976 | /// value. | |||
977 | /// | |||
978 | /// Uses of this method are potentially indicative of design problems: If it's | |||
979 | /// legitimate to do nothing while processing an "error", the error-producer | |||
980 | /// might be more clearly refactored to return an Optional<T>. | |||
981 | inline void consumeError(Error Err) { | |||
982 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); | |||
983 | } | |||
984 | ||||
985 | /// Helper for converting an Error to a bool. | |||
986 | /// | |||
987 | /// This method returns true if Err is in an error state, or false if it is | |||
988 | /// in a success state. Puts Err in a checked state in both cases (unlike | |||
989 | /// Error::operator bool(), which only does this for success states). | |||
990 | inline bool errorToBool(Error Err) { | |||
991 | bool IsError = static_cast<bool>(Err); | |||
992 | if (IsError) | |||
993 | consumeError(std::move(Err)); | |||
994 | return IsError; | |||
995 | } | |||
996 | ||||
997 | /// Helper for Errors used as out-parameters. | |||
998 | /// | |||
999 | /// This helper is for use with the Error-as-out-parameter idiom, where an error | |||
1000 | /// is passed to a function or method by reference, rather than being returned. | |||
1001 | /// In such cases it is helpful to set the checked bit on entry to the function | |||
1002 | /// so that the error can be written to (unchecked Errors abort on assignment) | |||
1003 | /// and clear the checked bit on exit so that clients cannot accidentally forget | |||
1004 | /// to check the result. This helper performs these actions automatically using | |||
1005 | /// RAII: | |||
1006 | /// | |||
1007 | /// @code{.cpp} | |||
1008 | /// Result foo(Error &Err) { | |||
1009 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set | |||
1010 | /// // <body of foo> | |||
1011 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. | |||
1012 | /// } | |||
1013 | /// @endcode | |||
1014 | /// | |||
1015 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be | |||
1016 | /// used with optional Errors (Error pointers that are allowed to be null). If | |||
1017 | /// ErrorAsOutParameter took an Error reference, an instance would have to be | |||
1018 | /// created inside every condition that verified that Error was non-null. By | |||
1019 | /// taking an Error pointer we can just create one instance at the top of the | |||
1020 | /// function. | |||
1021 | class ErrorAsOutParameter { | |||
1022 | public: | |||
1023 | ErrorAsOutParameter(Error *Err) : Err(Err) { | |||
1024 | // Raise the checked bit if Err is success. | |||
1025 | if (Err) | |||
1026 | (void)!!*Err; | |||
1027 | } | |||
1028 | ||||
1029 | ~ErrorAsOutParameter() { | |||
1030 | // Clear the checked bit. | |||
1031 | if (Err && !*Err) | |||
1032 | *Err = Error::success(); | |||
1033 | } | |||
1034 | ||||
1035 | private: | |||
1036 | Error *Err; | |||
1037 | }; | |||
1038 | ||||
1039 | /// Helper for Expected<T>s used as out-parameters. | |||
1040 | /// | |||
1041 | /// See ErrorAsOutParameter. | |||
1042 | template <typename T> | |||
1043 | class ExpectedAsOutParameter { | |||
1044 | public: | |||
1045 | ExpectedAsOutParameter(Expected<T> *ValOrErr) | |||
1046 | : ValOrErr(ValOrErr) { | |||
1047 | if (ValOrErr) | |||
1048 | (void)!!*ValOrErr; | |||
1049 | } | |||
1050 | ||||
1051 | ~ExpectedAsOutParameter() { | |||
1052 | if (ValOrErr) | |||
1053 | ValOrErr->setUnchecked(); | |||
1054 | } | |||
1055 | ||||
1056 | private: | |||
1057 | Expected<T> *ValOrErr; | |||
1058 | }; | |||
1059 | ||||
1060 | /// This class wraps a std::error_code in a Error. | |||
1061 | /// | |||
1062 | /// This is useful if you're writing an interface that returns a Error | |||
1063 | /// (or Expected) and you want to call code that still returns | |||
1064 | /// std::error_codes. | |||
1065 | class ECError : public ErrorInfo<ECError> { | |||
1066 | friend Error errorCodeToError(std::error_code); | |||
1067 | ||||
1068 | virtual void anchor() override; | |||
1069 | ||||
1070 | public: | |||
1071 | void setErrorCode(std::error_code EC) { this->EC = EC; } | |||
1072 | std::error_code convertToErrorCode() const override { return EC; } | |||
1073 | void log(raw_ostream &OS) const override { OS << EC.message(); } | |||
1074 | ||||
1075 | // Used by ErrorInfo::classID. | |||
1076 | static char ID; | |||
1077 | ||||
1078 | protected: | |||
1079 | ECError() = default; | |||
1080 | ECError(std::error_code EC) : EC(EC) {} | |||
1081 | ||||
1082 | std::error_code EC; | |||
1083 | }; | |||
1084 | ||||
1085 | /// The value returned by this function can be returned from convertToErrorCode | |||
1086 | /// for Error values where no sensible translation to std::error_code exists. | |||
1087 | /// It should only be used in this situation, and should never be used where a | |||
1088 | /// sensible conversion to std::error_code is available, as attempts to convert | |||
1089 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic | |||
1090 | ///error to try to convert such a value). | |||
1091 | std::error_code inconvertibleErrorCode(); | |||
1092 | ||||
1093 | /// Helper for converting an std::error_code to a Error. | |||
1094 | Error errorCodeToError(std::error_code EC); | |||
1095 | ||||
1096 | /// Helper for converting an ECError to a std::error_code. | |||
1097 | /// | |||
1098 | /// This method requires that Err be Error() or an ECError, otherwise it | |||
1099 | /// will trigger a call to abort(). | |||
1100 | std::error_code errorToErrorCode(Error Err); | |||
1101 | ||||
1102 | /// Convert an ErrorOr<T> to an Expected<T>. | |||
1103 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { | |||
1104 | if (auto EC = EO.getError()) | |||
1105 | return errorCodeToError(EC); | |||
1106 | return std::move(*EO); | |||
1107 | } | |||
1108 | ||||
1109 | /// Convert an Expected<T> to an ErrorOr<T>. | |||
1110 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { | |||
1111 | if (auto Err = E.takeError()) | |||
1112 | return errorToErrorCode(std::move(Err)); | |||
1113 | return std::move(*E); | |||
1114 | } | |||
1115 | ||||
1116 | /// This class wraps a string in an Error. | |||
1117 | /// | |||
1118 | /// StringError is useful in cases where the client is not expected to be able | |||
1119 | /// to consume the specific error message programmatically (for example, if the | |||
1120 | /// error message is to be presented to the user). | |||
1121 | /// | |||
1122 | /// StringError can also be used when additional information is to be printed | |||
1123 | /// along with a error_code message. Depending on the constructor called, this | |||
1124 | /// class can either display: | |||
1125 | /// 1. the error_code message (ECError behavior) | |||
1126 | /// 2. a string | |||
1127 | /// 3. the error_code message and a string | |||
1128 | /// | |||
1129 | /// These behaviors are useful when subtyping is required; for example, when a | |||
1130 | /// specific library needs an explicit error type. In the example below, | |||
1131 | /// PDBError is derived from StringError: | |||
1132 | /// | |||
1133 | /// @code{.cpp} | |||
1134 | /// Expected<int> foo() { | |||
1135 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, | |||
1136 | /// "Additional information"); | |||
1137 | /// } | |||
1138 | /// @endcode | |||
1139 | /// | |||
1140 | class StringError : public ErrorInfo<StringError> { | |||
1141 | public: | |||
1142 | static char ID; | |||
1143 | ||||
1144 | // Prints EC + S and converts to EC | |||
1145 | StringError(std::error_code EC, const Twine &S = Twine()); | |||
1146 | ||||
1147 | // Prints S and converts to EC | |||
1148 | StringError(const Twine &S, std::error_code EC); | |||
1149 | ||||
1150 | void log(raw_ostream &OS) const override; | |||
1151 | std::error_code convertToErrorCode() const override; | |||
1152 | ||||
1153 | const std::string &getMessage() const { return Msg; } | |||
1154 | ||||
1155 | private: | |||
1156 | std::string Msg; | |||
1157 | std::error_code EC; | |||
1158 | const bool PrintMsgOnly = false; | |||
1159 | }; | |||
1160 | ||||
1161 | /// Create formatted StringError object. | |||
1162 | template <typename... Ts> | |||
1163 | Error createStringError(std::error_code EC, char const *Fmt, | |||
1164 | const Ts &... Vals) { | |||
1165 | std::string Buffer; | |||
1166 | raw_string_ostream Stream(Buffer); | |||
1167 | Stream << format(Fmt, Vals...); | |||
1168 | return make_error<StringError>(Stream.str(), EC); | |||
1169 | } | |||
1170 | ||||
1171 | Error createStringError(std::error_code EC, char const *Msg); | |||
1172 | ||||
1173 | /// This class wraps a filename and another Error. | |||
1174 | /// | |||
1175 | /// In some cases, an error needs to live along a 'source' name, in order to | |||
1176 | /// show more detailed information to the user. | |||
1177 | class FileError final : public ErrorInfo<FileError> { | |||
1178 | ||||
1179 | friend Error createFileError(const Twine &, Error); | |||
1180 | friend Error createFileError(const Twine &, size_t, Error); | |||
1181 | ||||
1182 | public: | |||
1183 | void log(raw_ostream &OS) const override { | |||
1184 | assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()." ) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 1184, __PRETTY_FUNCTION__)); | |||
1185 | OS << "'" << FileName << "': "; | |||
1186 | if (Line.hasValue()) | |||
1187 | OS << "line " << Line.getValue() << ": "; | |||
1188 | Err->log(OS); | |||
1189 | } | |||
1190 | ||||
1191 | Error takeError() { return Error(std::move(Err)); } | |||
1192 | ||||
1193 | std::error_code convertToErrorCode() const override; | |||
1194 | ||||
1195 | // Used by ErrorInfo::classID. | |||
1196 | static char ID; | |||
1197 | ||||
1198 | private: | |||
1199 | FileError(const Twine &F, Optional<size_t> LineNum, | |||
1200 | std::unique_ptr<ErrorInfoBase> E) { | |||
1201 | assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value." ) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 1201, __PRETTY_FUNCTION__)); | |||
1202 | assert(!F.isTriviallyEmpty() &&((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 1203, __PRETTY_FUNCTION__)) | |||
1203 | "The file name provided to FileError must not be empty.")((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 1203, __PRETTY_FUNCTION__)); | |||
1204 | FileName = F.str(); | |||
1205 | Err = std::move(E); | |||
1206 | Line = std::move(LineNum); | |||
1207 | } | |||
1208 | ||||
1209 | static Error build(const Twine &F, Optional<size_t> Line, Error E) { | |||
1210 | return Error( | |||
1211 | std::unique_ptr<FileError>(new FileError(F, Line, E.takePayload()))); | |||
1212 | } | |||
1213 | ||||
1214 | std::string FileName; | |||
1215 | Optional<size_t> Line; | |||
1216 | std::unique_ptr<ErrorInfoBase> Err; | |||
1217 | }; | |||
1218 | ||||
1219 | /// Concatenate a source file path and/or name with an Error. The resulting | |||
1220 | /// Error is unchecked. | |||
1221 | inline Error createFileError(const Twine &F, Error E) { | |||
1222 | return FileError::build(F, Optional<size_t>(), std::move(E)); | |||
1223 | } | |||
1224 | ||||
1225 | /// Concatenate a source file path and/or name with line number and an Error. | |||
1226 | /// The resulting Error is unchecked. | |||
1227 | inline Error createFileError(const Twine &F, size_t Line, Error E) { | |||
1228 | return FileError::build(F, Optional<size_t>(Line), std::move(E)); | |||
1229 | } | |||
1230 | ||||
1231 | /// Concatenate a source file path and/or name with a std::error_code | |||
1232 | /// to form an Error object. | |||
1233 | inline Error createFileError(const Twine &F, std::error_code EC) { | |||
1234 | return createFileError(F, errorCodeToError(EC)); | |||
1235 | } | |||
1236 | ||||
1237 | /// Concatenate a source file path and/or name with line number and | |||
1238 | /// std::error_code to form an Error object. | |||
1239 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { | |||
1240 | return createFileError(F, Line, errorCodeToError(EC)); | |||
1241 | } | |||
1242 | ||||
1243 | Error createFileError(const Twine &F, ErrorSuccess) = delete; | |||
1244 | ||||
1245 | /// Helper for check-and-exit error handling. | |||
1246 | /// | |||
1247 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. | |||
1248 | /// | |||
1249 | class ExitOnError { | |||
1250 | public: | |||
1251 | /// Create an error on exit helper. | |||
1252 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) | |||
1253 | : Banner(std::move(Banner)), | |||
1254 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} | |||
1255 | ||||
1256 | /// Set the banner string for any errors caught by operator(). | |||
1257 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } | |||
1258 | ||||
1259 | /// Set the exit-code mapper function. | |||
1260 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { | |||
1261 | this->GetExitCode = std::move(GetExitCode); | |||
1262 | } | |||
1263 | ||||
1264 | /// Check Err. If it's in a failure state log the error(s) and exit. | |||
1265 | void operator()(Error Err) const { checkError(std::move(Err)); } | |||
1266 | ||||
1267 | /// Check E. If it's in a success state then return the contained value. If | |||
1268 | /// it's in a failure state log the error(s) and exit. | |||
1269 | template <typename T> T operator()(Expected<T> &&E) const { | |||
1270 | checkError(E.takeError()); | |||
1271 | return std::move(*E); | |||
1272 | } | |||
1273 | ||||
1274 | /// Check E. If it's in a success state then return the contained reference. If | |||
1275 | /// it's in a failure state log the error(s) and exit. | |||
1276 | template <typename T> T& operator()(Expected<T&> &&E) const { | |||
1277 | checkError(E.takeError()); | |||
1278 | return *E; | |||
1279 | } | |||
1280 | ||||
1281 | private: | |||
1282 | void checkError(Error Err) const { | |||
1283 | if (Err) { | |||
1284 | int ExitCode = GetExitCode(Err); | |||
1285 | logAllUnhandledErrors(std::move(Err), errs(), Banner); | |||
1286 | exit(ExitCode); | |||
1287 | } | |||
1288 | } | |||
1289 | ||||
1290 | std::string Banner; | |||
1291 | std::function<int(const Error &)> GetExitCode; | |||
1292 | }; | |||
1293 | ||||
1294 | /// Conversion from Error to LLVMErrorRef for C error bindings. | |||
1295 | inline LLVMErrorRef wrap(Error Err) { | |||
1296 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); | |||
1297 | } | |||
1298 | ||||
1299 | /// Conversion from LLVMErrorRef to Error for C error bindings. | |||
1300 | inline Error unwrap(LLVMErrorRef ErrRef) { | |||
1301 | return Error(std::unique_ptr<ErrorInfoBase>( | |||
1302 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); | |||
1303 | } | |||
1304 | ||||
1305 | } // end namespace llvm | |||
1306 | ||||
1307 | #endif // LLVM_SUPPORT_ERROR_H |
1 | //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file contains some templates that are useful if you are working with the |
10 | // STL at all. |
11 | // |
12 | // No library is required when using these functions. |
13 | // |
14 | //===----------------------------------------------------------------------===// |
15 | |
16 | #ifndef LLVM_ADT_STLEXTRAS_H |
17 | #define LLVM_ADT_STLEXTRAS_H |
18 | |
19 | #include "llvm/ADT/Optional.h" |
20 | #include "llvm/ADT/SmallVector.h" |
21 | #include "llvm/ADT/iterator.h" |
22 | #include "llvm/ADT/iterator_range.h" |
23 | #include "llvm/Config/abi-breaking.h" |
24 | #include "llvm/Support/ErrorHandling.h" |
25 | #include <algorithm> |
26 | #include <cassert> |
27 | #include <cstddef> |
28 | #include <cstdint> |
29 | #include <cstdlib> |
30 | #include <functional> |
31 | #include <initializer_list> |
32 | #include <iterator> |
33 | #include <limits> |
34 | #include <memory> |
35 | #include <tuple> |
36 | #include <type_traits> |
37 | #include <utility> |
38 | |
39 | #ifdef EXPENSIVE_CHECKS |
40 | #include <random> // for std::mt19937 |
41 | #endif |
42 | |
43 | namespace llvm { |
44 | |
45 | // Only used by compiler if both template types are the same. Useful when |
46 | // using SFINAE to test for the existence of member functions. |
47 | template <typename T, T> struct SameType; |
48 | |
49 | namespace detail { |
50 | |
51 | template <typename RangeT> |
52 | using IterOfRange = decltype(std::begin(std::declval<RangeT &>())); |
53 | |
54 | template <typename RangeT> |
55 | using ValueOfRange = typename std::remove_reference<decltype( |
56 | *std::begin(std::declval<RangeT &>()))>::type; |
57 | |
58 | } // end namespace detail |
59 | |
60 | //===----------------------------------------------------------------------===// |
61 | // Extra additions to <type_traits> |
62 | //===----------------------------------------------------------------------===// |
63 | |
64 | template <typename T> |
65 | struct negation : std::integral_constant<bool, !bool(T::value)> {}; |
66 | |
67 | template <typename...> struct conjunction : std::true_type {}; |
68 | template <typename B1> struct conjunction<B1> : B1 {}; |
69 | template <typename B1, typename... Bn> |
70 | struct conjunction<B1, Bn...> |
71 | : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; |
72 | |
73 | template <typename T> struct make_const_ptr { |
74 | using type = |
75 | typename std::add_pointer<typename std::add_const<T>::type>::type; |
76 | }; |
77 | |
78 | template <typename T> struct make_const_ref { |
79 | using type = typename std::add_lvalue_reference< |
80 | typename std::add_const<T>::type>::type; |
81 | }; |
82 | |
83 | //===----------------------------------------------------------------------===// |
84 | // Extra additions to <functional> |
85 | //===----------------------------------------------------------------------===// |
86 | |
87 | template <class Ty> struct identity { |
88 | using argument_type = Ty; |
89 | |
90 | Ty &operator()(Ty &self) const { |
91 | return self; |
92 | } |
93 | const Ty &operator()(const Ty &self) const { |
94 | return self; |
95 | } |
96 | }; |
97 | |
98 | template <class Ty> struct less_ptr { |
99 | bool operator()(const Ty* left, const Ty* right) const { |
100 | return *left < *right; |
101 | } |
102 | }; |
103 | |
104 | template <class Ty> struct greater_ptr { |
105 | bool operator()(const Ty* left, const Ty* right) const { |
106 | return *right < *left; |
107 | } |
108 | }; |
109 | |
110 | /// An efficient, type-erasing, non-owning reference to a callable. This is |
111 | /// intended for use as the type of a function parameter that is not used |
112 | /// after the function in question returns. |
113 | /// |
114 | /// This class does not own the callable, so it is not in general safe to store |
115 | /// a function_ref. |
116 | template<typename Fn> class function_ref; |
117 | |
118 | template<typename Ret, typename ...Params> |
119 | class function_ref<Ret(Params...)> { |
120 | Ret (*callback)(intptr_t callable, Params ...params) = nullptr; |
121 | intptr_t callable; |
122 | |
123 | template<typename Callable> |
124 | static Ret callback_fn(intptr_t callable, Params ...params) { |
125 | return (*reinterpret_cast<Callable*>(callable))( |
126 | std::forward<Params>(params)...); |
127 | } |
128 | |
129 | public: |
130 | function_ref() = default; |
131 | function_ref(std::nullptr_t) {} |
132 | |
133 | template <typename Callable> |
134 | function_ref(Callable &&callable, |
135 | typename std::enable_if< |
136 | !std::is_same<typename std::remove_reference<Callable>::type, |
137 | function_ref>::value>::type * = nullptr) |
138 | : callback(callback_fn<typename std::remove_reference<Callable>::type>), |
139 | callable(reinterpret_cast<intptr_t>(&callable)) {} |
140 | |
141 | Ret operator()(Params ...params) const { |
142 | return callback(callable, std::forward<Params>(params)...); |
143 | } |
144 | |
145 | operator bool() const { return callback; } |
146 | }; |
147 | |
148 | // deleter - Very very very simple method that is used to invoke operator |
149 | // delete on something. It is used like this: |
150 | // |
151 | // for_each(V.begin(), B.end(), deleter<Interval>); |
152 | template <class T> |
153 | inline void deleter(T *Ptr) { |
154 | delete Ptr; |
155 | } |
156 | |
157 | //===----------------------------------------------------------------------===// |
158 | // Extra additions to <iterator> |
159 | //===----------------------------------------------------------------------===// |
160 | |
161 | namespace adl_detail { |
162 | |
163 | using std::begin; |
164 | |
165 | template <typename ContainerTy> |
166 | auto adl_begin(ContainerTy &&container) |
167 | -> decltype(begin(std::forward<ContainerTy>(container))) { |
168 | return begin(std::forward<ContainerTy>(container)); |
169 | } |
170 | |
171 | using std::end; |
172 | |
173 | template <typename ContainerTy> |
174 | auto adl_end(ContainerTy &&container) |
175 | -> decltype(end(std::forward<ContainerTy>(container))) { |
176 | return end(std::forward<ContainerTy>(container)); |
177 | } |
178 | |
179 | using std::swap; |
180 | |
181 | template <typename T> |
182 | void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(), |
183 | std::declval<T>()))) { |
184 | swap(std::forward<T>(lhs), std::forward<T>(rhs)); |
185 | } |
186 | |
187 | } // end namespace adl_detail |
188 | |
189 | template <typename ContainerTy> |
190 | auto adl_begin(ContainerTy &&container) |
191 | -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) { |
192 | return adl_detail::adl_begin(std::forward<ContainerTy>(container)); |
193 | } |
194 | |
195 | template <typename ContainerTy> |
196 | auto adl_end(ContainerTy &&container) |
197 | -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) { |
198 | return adl_detail::adl_end(std::forward<ContainerTy>(container)); |
199 | } |
200 | |
201 | template <typename T> |
202 | void adl_swap(T &&lhs, T &&rhs) noexcept( |
203 | noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) { |
204 | adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs)); |
205 | } |
206 | |
207 | /// Test whether \p RangeOrContainer is empty. Similar to C++17 std::empty. |
208 | template <typename T> |
209 | constexpr bool empty(const T &RangeOrContainer) { |
210 | return adl_begin(RangeOrContainer) == adl_end(RangeOrContainer); |
211 | } |
212 | |
213 | // mapped_iterator - This is a simple iterator adapter that causes a function to |
214 | // be applied whenever operator* is invoked on the iterator. |
215 | |
216 | template <typename ItTy, typename FuncTy, |
217 | typename FuncReturnTy = |
218 | decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))> |
219 | class mapped_iterator |
220 | : public iterator_adaptor_base< |
221 | mapped_iterator<ItTy, FuncTy>, ItTy, |
222 | typename std::iterator_traits<ItTy>::iterator_category, |
223 | typename std::remove_reference<FuncReturnTy>::type> { |
224 | public: |
225 | mapped_iterator(ItTy U, FuncTy F) |
226 | : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {} |
227 | |
228 | ItTy getCurrent() { return this->I; } |
229 | |
230 | FuncReturnTy operator*() { return F(*this->I); } |
231 | |
232 | private: |
233 | FuncTy F; |
234 | }; |
235 | |
236 | // map_iterator - Provide a convenient way to create mapped_iterators, just like |
237 | // make_pair is useful for creating pairs... |
238 | template <class ItTy, class FuncTy> |
239 | inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) { |
240 | return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F)); |
241 | } |
242 | |
243 | /// Helper to determine if type T has a member called rbegin(). |
244 | template <typename Ty> class has_rbegin_impl { |
245 | using yes = char[1]; |
246 | using no = char[2]; |
247 | |
248 | template <typename Inner> |
249 | static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr); |
250 | |
251 | template <typename> |
252 | static no& test(...); |
253 | |
254 | public: |
255 | static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); |
256 | }; |
257 | |
258 | /// Metafunction to determine if T& or T has a member called rbegin(). |
259 | template <typename Ty> |
260 | struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> { |
261 | }; |
262 | |
263 | // Returns an iterator_range over the given container which iterates in reverse. |
264 | // Note that the container must have rbegin()/rend() methods for this to work. |
265 | template <typename ContainerTy> |
266 | auto reverse(ContainerTy &&C, |
267 | typename std::enable_if<has_rbegin<ContainerTy>::value>::type * = |
268 | nullptr) -> decltype(make_range(C.rbegin(), C.rend())) { |
269 | return make_range(C.rbegin(), C.rend()); |
270 | } |
271 | |
272 | // Returns a std::reverse_iterator wrapped around the given iterator. |
273 | template <typename IteratorTy> |
274 | std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) { |
275 | return std::reverse_iterator<IteratorTy>(It); |
276 | } |
277 | |
278 | // Returns an iterator_range over the given container which iterates in reverse. |
279 | // Note that the container must have begin()/end() methods which return |
280 | // bidirectional iterators for this to work. |
281 | template <typename ContainerTy> |
282 | auto reverse( |
283 | ContainerTy &&C, |
284 | typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr) |
285 | -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)), |
286 | llvm::make_reverse_iterator(std::begin(C)))) { |
287 | return make_range(llvm::make_reverse_iterator(std::end(C)), |
288 | llvm::make_reverse_iterator(std::begin(C))); |
289 | } |
290 | |
291 | /// An iterator adaptor that filters the elements of given inner iterators. |
292 | /// |
293 | /// The predicate parameter should be a callable object that accepts the wrapped |
294 | /// iterator's reference type and returns a bool. When incrementing or |
295 | /// decrementing the iterator, it will call the predicate on each element and |
296 | /// skip any where it returns false. |
297 | /// |
298 | /// \code |
299 | /// int A[] = { 1, 2, 3, 4 }; |
300 | /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; }); |
301 | /// // R contains { 1, 3 }. |
302 | /// \endcode |
303 | /// |
304 | /// Note: filter_iterator_base implements support for forward iteration. |
305 | /// filter_iterator_impl exists to provide support for bidirectional iteration, |
306 | /// conditional on whether the wrapped iterator supports it. |
307 | template <typename WrappedIteratorT, typename PredicateT, typename IterTag> |
308 | class filter_iterator_base |
309 | : public iterator_adaptor_base< |
310 | filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>, |
311 | WrappedIteratorT, |
312 | typename std::common_type< |
313 | IterTag, typename std::iterator_traits< |
314 | WrappedIteratorT>::iterator_category>::type> { |
315 | using BaseT = iterator_adaptor_base< |
316 | filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>, |
317 | WrappedIteratorT, |
318 | typename std::common_type< |
319 | IterTag, typename std::iterator_traits< |
320 | WrappedIteratorT>::iterator_category>::type>; |
321 | |
322 | protected: |
323 | WrappedIteratorT End; |
324 | PredicateT Pred; |
325 | |
326 | void findNextValid() { |
327 | while (this->I != End && !Pred(*this->I)) |
328 | BaseT::operator++(); |
329 | } |
330 | |
331 | // Construct the iterator. The begin iterator needs to know where the end |
332 | // is, so that it can properly stop when it gets there. The end iterator only |
333 | // needs the predicate to support bidirectional iteration. |
334 | filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, |
335 | PredicateT Pred) |
336 | : BaseT(Begin), End(End), Pred(Pred) { |
337 | findNextValid(); |
338 | } |
339 | |
340 | public: |
341 | using BaseT::operator++; |
342 | |
343 | filter_iterator_base &operator++() { |
344 | BaseT::operator++(); |
345 | findNextValid(); |
346 | return *this; |
347 | } |
348 | }; |
349 | |
350 | /// Specialization of filter_iterator_base for forward iteration only. |
351 | template <typename WrappedIteratorT, typename PredicateT, |
352 | typename IterTag = std::forward_iterator_tag> |
353 | class filter_iterator_impl |
354 | : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> { |
355 | using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>; |
356 | |
357 | public: |
358 | filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, |
359 | PredicateT Pred) |
360 | : BaseT(Begin, End, Pred) {} |
361 | }; |
362 | |
363 | /// Specialization of filter_iterator_base for bidirectional iteration. |
364 | template <typename WrappedIteratorT, typename PredicateT> |
365 | class filter_iterator_impl<WrappedIteratorT, PredicateT, |
366 | std::bidirectional_iterator_tag> |
367 | : public filter_iterator_base<WrappedIteratorT, PredicateT, |
368 | std::bidirectional_iterator_tag> { |
369 | using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, |
370 | std::bidirectional_iterator_tag>; |
371 | void findPrevValid() { |
372 | while (!this->Pred(*this->I)) |
373 | BaseT::operator--(); |
374 | } |
375 | |
376 | public: |
377 | using BaseT::operator--; |
378 | |
379 | filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, |
380 | PredicateT Pred) |
381 | : BaseT(Begin, End, Pred) {} |
382 | |
383 | filter_iterator_impl &operator--() { |
384 | BaseT::operator--(); |
385 | findPrevValid(); |
386 | return *this; |
387 | } |
388 | }; |
389 | |
390 | namespace detail { |
391 | |
392 | template <bool is_bidirectional> struct fwd_or_bidi_tag_impl { |
393 | using type = std::forward_iterator_tag; |
394 | }; |
395 | |
396 | template <> struct fwd_or_bidi_tag_impl<true> { |
397 | using type = std::bidirectional_iterator_tag; |
398 | }; |
399 | |
400 | /// Helper which sets its type member to forward_iterator_tag if the category |
401 | /// of \p IterT does not derive from bidirectional_iterator_tag, and to |
402 | /// bidirectional_iterator_tag otherwise. |
403 | template <typename IterT> struct fwd_or_bidi_tag { |
404 | using type = typename fwd_or_bidi_tag_impl<std::is_base_of< |
405 | std::bidirectional_iterator_tag, |
406 | typename std::iterator_traits<IterT>::iterator_category>::value>::type; |
407 | }; |
408 | |
409 | } // namespace detail |
410 | |
411 | /// Defines filter_iterator to a suitable specialization of |
412 | /// filter_iterator_impl, based on the underlying iterator's category. |
413 | template <typename WrappedIteratorT, typename PredicateT> |
414 | using filter_iterator = filter_iterator_impl< |
415 | WrappedIteratorT, PredicateT, |
416 | typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>; |
417 | |
418 | /// Convenience function that takes a range of elements and a predicate, |
419 | /// and return a new filter_iterator range. |
420 | /// |
421 | /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the |
422 | /// lifetime of that temporary is not kept by the returned range object, and the |
423 | /// temporary is going to be dropped on the floor after the make_iterator_range |
424 | /// full expression that contains this function call. |
425 | template <typename RangeT, typename PredicateT> |
426 | iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>> |
427 | make_filter_range(RangeT &&Range, PredicateT Pred) { |
428 | using FilterIteratorT = |
429 | filter_iterator<detail::IterOfRange<RangeT>, PredicateT>; |
430 | return make_range( |
431 | FilterIteratorT(std::begin(std::forward<RangeT>(Range)), |
432 | std::end(std::forward<RangeT>(Range)), Pred), |
433 | FilterIteratorT(std::end(std::forward<RangeT>(Range)), |
434 | std::end(std::forward<RangeT>(Range)), Pred)); |
435 | } |
436 | |
437 | /// A pseudo-iterator adaptor that is designed to implement "early increment" |
438 | /// style loops. |
439 | /// |
440 | /// This is *not a normal iterator* and should almost never be used directly. It |
441 | /// is intended primarily to be used with range based for loops and some range |
442 | /// algorithms. |
443 | /// |
444 | /// The iterator isn't quite an `OutputIterator` or an `InputIterator` but |
445 | /// somewhere between them. The constraints of these iterators are: |
446 | /// |
447 | /// - On construction or after being incremented, it is comparable and |
448 | /// dereferencable. It is *not* incrementable. |
449 | /// - After being dereferenced, it is neither comparable nor dereferencable, it |
450 | /// is only incrementable. |
451 | /// |
452 | /// This means you can only dereference the iterator once, and you can only |
453 | /// increment it once between dereferences. |
454 | template <typename WrappedIteratorT> |
455 | class early_inc_iterator_impl |
456 | : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>, |
457 | WrappedIteratorT, std::input_iterator_tag> { |
458 | using BaseT = |
459 | iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>, |
460 | WrappedIteratorT, std::input_iterator_tag>; |
461 | |
462 | using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer; |
463 | |
464 | protected: |
465 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
466 | bool IsEarlyIncremented = false; |
467 | #endif |
468 | |
469 | public: |
470 | early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {} |
471 | |
472 | using BaseT::operator*; |
473 | typename BaseT::reference operator*() { |
474 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
475 | assert(!IsEarlyIncremented && "Cannot dereference twice!")((!IsEarlyIncremented && "Cannot dereference twice!") ? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot dereference twice!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 475, __PRETTY_FUNCTION__)); |
476 | IsEarlyIncremented = true; |
477 | #endif |
478 | return *(this->I)++; |
479 | } |
480 | |
481 | using BaseT::operator++; |
482 | early_inc_iterator_impl &operator++() { |
483 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
484 | assert(IsEarlyIncremented && "Cannot increment before dereferencing!")((IsEarlyIncremented && "Cannot increment before dereferencing!" ) ? static_cast<void> (0) : __assert_fail ("IsEarlyIncremented && \"Cannot increment before dereferencing!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 484, __PRETTY_FUNCTION__)); |
485 | IsEarlyIncremented = false; |
486 | #endif |
487 | return *this; |
488 | } |
489 | |
490 | using BaseT::operator==; |
491 | bool operator==(const early_inc_iterator_impl &RHS) const { |
492 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
493 | assert(!IsEarlyIncremented && "Cannot compare after dereferencing!")((!IsEarlyIncremented && "Cannot compare after dereferencing!" ) ? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot compare after dereferencing!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 493, __PRETTY_FUNCTION__)); |
494 | #endif |
495 | return BaseT::operator==(RHS); |
496 | } |
497 | }; |
498 | |
499 | /// Make a range that does early increment to allow mutation of the underlying |
500 | /// range without disrupting iteration. |
501 | /// |
502 | /// The underlying iterator will be incremented immediately after it is |
503 | /// dereferenced, allowing deletion of the current node or insertion of nodes to |
504 | /// not disrupt iteration provided they do not invalidate the *next* iterator -- |
505 | /// the current iterator can be invalidated. |
506 | /// |
507 | /// This requires a very exact pattern of use that is only really suitable to |
508 | /// range based for loops and other range algorithms that explicitly guarantee |
509 | /// to dereference exactly once each element, and to increment exactly once each |
510 | /// element. |
511 | template <typename RangeT> |
512 | iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>> |
513 | make_early_inc_range(RangeT &&Range) { |
514 | using EarlyIncIteratorT = |
515 | early_inc_iterator_impl<detail::IterOfRange<RangeT>>; |
516 | return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))), |
517 | EarlyIncIteratorT(std::end(std::forward<RangeT>(Range)))); |
518 | } |
519 | |
520 | // forward declarations required by zip_shortest/zip_first/zip_longest |
521 | template <typename R, typename UnaryPredicate> |
522 | bool all_of(R &&range, UnaryPredicate P); |
523 | template <typename R, typename UnaryPredicate> |
524 | bool any_of(R &&range, UnaryPredicate P); |
525 | |
526 | template <size_t... I> struct index_sequence; |
527 | |
528 | template <class... Ts> struct index_sequence_for; |
529 | |
530 | namespace detail { |
531 | |
532 | using std::declval; |
533 | |
534 | // We have to alias this since inlining the actual type at the usage site |
535 | // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017. |
536 | template<typename... Iters> struct ZipTupleType { |
537 | using type = std::tuple<decltype(*declval<Iters>())...>; |
538 | }; |
539 | |
540 | template <typename ZipType, typename... Iters> |
541 | using zip_traits = iterator_facade_base< |
542 | ZipType, typename std::common_type<std::bidirectional_iterator_tag, |
543 | typename std::iterator_traits< |
544 | Iters>::iterator_category...>::type, |
545 | // ^ TODO: Implement random access methods. |
546 | typename ZipTupleType<Iters...>::type, |
547 | typename std::iterator_traits<typename std::tuple_element< |
548 | 0, std::tuple<Iters...>>::type>::difference_type, |
549 | // ^ FIXME: This follows boost::make_zip_iterator's assumption that all |
550 | // inner iterators have the same difference_type. It would fail if, for |
551 | // instance, the second field's difference_type were non-numeric while the |
552 | // first is. |
553 | typename ZipTupleType<Iters...>::type *, |
554 | typename ZipTupleType<Iters...>::type>; |
555 | |
556 | template <typename ZipType, typename... Iters> |
557 | struct zip_common : public zip_traits<ZipType, Iters...> { |
558 | using Base = zip_traits<ZipType, Iters...>; |
559 | using value_type = typename Base::value_type; |
560 | |
561 | std::tuple<Iters...> iterators; |
562 | |
563 | protected: |
564 | template <size_t... Ns> value_type deref(index_sequence<Ns...>) const { |
565 | return value_type(*std::get<Ns>(iterators)...); |
566 | } |
567 | |
568 | template <size_t... Ns> |
569 | decltype(iterators) tup_inc(index_sequence<Ns...>) const { |
570 | return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...); |
571 | } |
572 | |
573 | template <size_t... Ns> |
574 | decltype(iterators) tup_dec(index_sequence<Ns...>) const { |
575 | return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...); |
576 | } |
577 | |
578 | public: |
579 | zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {} |
580 | |
581 | value_type operator*() { return deref(index_sequence_for<Iters...>{}); } |
582 | |
583 | const value_type operator*() const { |
584 | return deref(index_sequence_for<Iters...>{}); |
585 | } |
586 | |
587 | ZipType &operator++() { |
588 | iterators = tup_inc(index_sequence_for<Iters...>{}); |
589 | return *reinterpret_cast<ZipType *>(this); |
590 | } |
591 | |
592 | ZipType &operator--() { |
593 | static_assert(Base::IsBidirectional, |
594 | "All inner iterators must be at least bidirectional."); |
595 | iterators = tup_dec(index_sequence_for<Iters...>{}); |
596 | return *reinterpret_cast<ZipType *>(this); |
597 | } |
598 | }; |
599 | |
600 | template <typename... Iters> |
601 | struct zip_first : public zip_common<zip_first<Iters...>, Iters...> { |
602 | using Base = zip_common<zip_first<Iters...>, Iters...>; |
603 | |
604 | bool operator==(const zip_first<Iters...> &other) const { |
605 | return std::get<0>(this->iterators) == std::get<0>(other.iterators); |
606 | } |
607 | |
608 | zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} |
609 | }; |
610 | |
611 | template <typename... Iters> |
612 | class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> { |
613 | template <size_t... Ns> |
614 | bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const { |
615 | return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) != |
616 | std::get<Ns>(other.iterators)...}, |
617 | identity<bool>{}); |
618 | } |
619 | |
620 | public: |
621 | using Base = zip_common<zip_shortest<Iters...>, Iters...>; |
622 | |
623 | zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} |
624 | |
625 | bool operator==(const zip_shortest<Iters...> &other) const { |
626 | return !test(other, index_sequence_for<Iters...>{}); |
627 | } |
628 | }; |
629 | |
630 | template <template <typename...> class ItType, typename... Args> class zippy { |
631 | public: |
632 | using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>; |
633 | using iterator_category = typename iterator::iterator_category; |
634 | using value_type = typename iterator::value_type; |
635 | using difference_type = typename iterator::difference_type; |
636 | using pointer = typename iterator::pointer; |
637 | using reference = typename iterator::reference; |
638 | |
639 | private: |
640 | std::tuple<Args...> ts; |
641 | |
642 | template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const { |
643 | return iterator(std::begin(std::get<Ns>(ts))...); |
644 | } |
645 | template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const { |
646 | return iterator(std::end(std::get<Ns>(ts))...); |
647 | } |
648 | |
649 | public: |
650 | zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} |
651 | |
652 | iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); } |
653 | iterator end() const { return end_impl(index_sequence_for<Args...>{}); } |
654 | }; |
655 | |
656 | } // end namespace detail |
657 | |
658 | /// zip iterator for two or more iteratable types. |
659 | template <typename T, typename U, typename... Args> |
660 | detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u, |
661 | Args &&... args) { |
662 | return detail::zippy<detail::zip_shortest, T, U, Args...>( |
663 | std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); |
664 | } |
665 | |
666 | /// zip iterator that, for the sake of efficiency, assumes the first iteratee to |
667 | /// be the shortest. |
668 | template <typename T, typename U, typename... Args> |
669 | detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u, |
670 | Args &&... args) { |
671 | return detail::zippy<detail::zip_first, T, U, Args...>( |
672 | std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); |
673 | } |
674 | |
675 | namespace detail { |
676 | template <typename Iter> |
677 | static Iter next_or_end(const Iter &I, const Iter &End) { |
678 | if (I == End) |
679 | return End; |
680 | return std::next(I); |
681 | } |
682 | |
683 | template <typename Iter> |
684 | static auto deref_or_none(const Iter &I, const Iter &End) |
685 | -> llvm::Optional<typename std::remove_const< |
686 | typename std::remove_reference<decltype(*I)>::type>::type> { |
687 | if (I == End) |
688 | return None; |
689 | return *I; |
690 | } |
691 | |
692 | template <typename Iter> struct ZipLongestItemType { |
693 | using type = |
694 | llvm::Optional<typename std::remove_const<typename std::remove_reference< |
695 | decltype(*std::declval<Iter>())>::type>::type>; |
696 | }; |
697 | |
698 | template <typename... Iters> struct ZipLongestTupleType { |
699 | using type = std::tuple<typename ZipLongestItemType<Iters>::type...>; |
700 | }; |
701 | |
702 | template <typename... Iters> |
703 | class zip_longest_iterator |
704 | : public iterator_facade_base< |
705 | zip_longest_iterator<Iters...>, |
706 | typename std::common_type< |
707 | std::forward_iterator_tag, |
708 | typename std::iterator_traits<Iters>::iterator_category...>::type, |
709 | typename ZipLongestTupleType<Iters...>::type, |
710 | typename std::iterator_traits<typename std::tuple_element< |
711 | 0, std::tuple<Iters...>>::type>::difference_type, |
712 | typename ZipLongestTupleType<Iters...>::type *, |
713 | typename ZipLongestTupleType<Iters...>::type> { |
714 | public: |
715 | using value_type = typename ZipLongestTupleType<Iters...>::type; |
716 | |
717 | private: |
718 | std::tuple<Iters...> iterators; |
719 | std::tuple<Iters...> end_iterators; |
720 | |
721 | template <size_t... Ns> |
722 | bool test(const zip_longest_iterator<Iters...> &other, |
723 | index_sequence<Ns...>) const { |
724 | return llvm::any_of( |
725 | std::initializer_list<bool>{std::get<Ns>(this->iterators) != |
726 | std::get<Ns>(other.iterators)...}, |
727 | identity<bool>{}); |
728 | } |
729 | |
730 | template <size_t... Ns> value_type deref(index_sequence<Ns...>) const { |
731 | return value_type( |
732 | deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); |
733 | } |
734 | |
735 | template <size_t... Ns> |
736 | decltype(iterators) tup_inc(index_sequence<Ns...>) const { |
737 | return std::tuple<Iters...>( |
738 | next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); |
739 | } |
740 | |
741 | public: |
742 | zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts) |
743 | : iterators(std::forward<Iters>(ts.first)...), |
744 | end_iterators(std::forward<Iters>(ts.second)...) {} |
745 | |
746 | value_type operator*() { return deref(index_sequence_for<Iters...>{}); } |
747 | |
748 | value_type operator*() const { return deref(index_sequence_for<Iters...>{}); } |
749 | |
750 | zip_longest_iterator<Iters...> &operator++() { |
751 | iterators = tup_inc(index_sequence_for<Iters...>{}); |
752 | return *this; |
753 | } |
754 | |
755 | bool operator==(const zip_longest_iterator<Iters...> &other) const { |
756 | return !test(other, index_sequence_for<Iters...>{}); |
757 | } |
758 | }; |
759 | |
760 | template <typename... Args> class zip_longest_range { |
761 | public: |
762 | using iterator = |
763 | zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>; |
764 | using iterator_category = typename iterator::iterator_category; |
765 | using value_type = typename iterator::value_type; |
766 | using difference_type = typename iterator::difference_type; |
767 | using pointer = typename iterator::pointer; |
768 | using reference = typename iterator::reference; |
769 | |
770 | private: |
771 | std::tuple<Args...> ts; |
772 | |
773 | template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const { |
774 | return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)), |
775 | adl_end(std::get<Ns>(ts)))...); |
776 | } |
777 | |
778 | template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const { |
779 | return iterator(std::make_pair(adl_end(std::get<Ns>(ts)), |
780 | adl_end(std::get<Ns>(ts)))...); |
781 | } |
782 | |
783 | public: |
784 | zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} |
785 | |
786 | iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); } |
787 | iterator end() const { return end_impl(index_sequence_for<Args...>{}); } |
788 | }; |
789 | } // namespace detail |
790 | |
791 | /// Iterate over two or more iterators at the same time. Iteration continues |
792 | /// until all iterators reach the end. The llvm::Optional only contains a value |
793 | /// if the iterator has not reached the end. |
794 | template <typename T, typename U, typename... Args> |
795 | detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u, |
796 | Args &&... args) { |
797 | return detail::zip_longest_range<T, U, Args...>( |
798 | std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); |
799 | } |
800 | |
801 | /// Iterator wrapper that concatenates sequences together. |
802 | /// |
803 | /// This can concatenate different iterators, even with different types, into |
804 | /// a single iterator provided the value types of all the concatenated |
805 | /// iterators expose `reference` and `pointer` types that can be converted to |
806 | /// `ValueT &` and `ValueT *` respectively. It doesn't support more |
807 | /// interesting/customized pointer or reference types. |
808 | /// |
809 | /// Currently this only supports forward or higher iterator categories as |
810 | /// inputs and always exposes a forward iterator interface. |
811 | template <typename ValueT, typename... IterTs> |
812 | class concat_iterator |
813 | : public iterator_facade_base<concat_iterator<ValueT, IterTs...>, |
814 | std::forward_iterator_tag, ValueT> { |
815 | using BaseT = typename concat_iterator::iterator_facade_base; |
816 | |
817 | /// We store both the current and end iterators for each concatenated |
818 | /// sequence in a tuple of pairs. |
819 | /// |
820 | /// Note that something like iterator_range seems nice at first here, but the |
821 | /// range properties are of little benefit and end up getting in the way |
822 | /// because we need to do mutation on the current iterators. |
823 | std::tuple<IterTs...> Begins; |
824 | std::tuple<IterTs...> Ends; |
825 | |
826 | /// Attempts to increment a specific iterator. |
827 | /// |
828 | /// Returns true if it was able to increment the iterator. Returns false if |
829 | /// the iterator is already at the end iterator. |
830 | template <size_t Index> bool incrementHelper() { |
831 | auto &Begin = std::get<Index>(Begins); |
832 | auto &End = std::get<Index>(Ends); |
833 | if (Begin == End) |
834 | return false; |
835 | |
836 | ++Begin; |
837 | return true; |
838 | } |
839 | |
840 | /// Increments the first non-end iterator. |
841 | /// |
842 | /// It is an error to call this with all iterators at the end. |
843 | template <size_t... Ns> void increment(index_sequence<Ns...>) { |
844 | // Build a sequence of functions to increment each iterator if possible. |
845 | bool (concat_iterator::*IncrementHelperFns[])() = { |
846 | &concat_iterator::incrementHelper<Ns>...}; |
847 | |
848 | // Loop over them, and stop as soon as we succeed at incrementing one. |
849 | for (auto &IncrementHelperFn : IncrementHelperFns) |
850 | if ((this->*IncrementHelperFn)()) |
851 | return; |
852 | |
853 | llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 853); |
854 | } |
855 | |
856 | /// Returns null if the specified iterator is at the end. Otherwise, |
857 | /// dereferences the iterator and returns the address of the resulting |
858 | /// reference. |
859 | template <size_t Index> ValueT *getHelper() const { |
860 | auto &Begin = std::get<Index>(Begins); |
861 | auto &End = std::get<Index>(Ends); |
862 | if (Begin == End) |
863 | return nullptr; |
864 | |
865 | return &*Begin; |
866 | } |
867 | |
868 | /// Finds the first non-end iterator, dereferences, and returns the resulting |
869 | /// reference. |
870 | /// |
871 | /// It is an error to call this with all iterators at the end. |
872 | template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const { |
873 | // Build a sequence of functions to get from iterator if possible. |
874 | ValueT *(concat_iterator::*GetHelperFns[])() const = { |
875 | &concat_iterator::getHelper<Ns>...}; |
876 | |
877 | // Loop over them, and return the first result we find. |
878 | for (auto &GetHelperFn : GetHelperFns) |
879 | if (ValueT *P = (this->*GetHelperFn)()) |
880 | return *P; |
881 | |
882 | llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 882); |
883 | } |
884 | |
885 | public: |
886 | /// Constructs an iterator from a squence of ranges. |
887 | /// |
888 | /// We need the full range to know how to switch between each of the |
889 | /// iterators. |
890 | template <typename... RangeTs> |
891 | explicit concat_iterator(RangeTs &&... Ranges) |
892 | : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {} |
893 | |
894 | using BaseT::operator++; |
895 | |
896 | concat_iterator &operator++() { |
897 | increment(index_sequence_for<IterTs...>()); |
898 | return *this; |
899 | } |
900 | |
901 | ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); } |
902 | |
903 | bool operator==(const concat_iterator &RHS) const { |
904 | return Begins == RHS.Begins && Ends == RHS.Ends; |
905 | } |
906 | }; |
907 | |
908 | namespace detail { |
909 | |
910 | /// Helper to store a sequence of ranges being concatenated and access them. |
911 | /// |
912 | /// This is designed to facilitate providing actual storage when temporaries |
913 | /// are passed into the constructor such that we can use it as part of range |
914 | /// based for loops. |
915 | template <typename ValueT, typename... RangeTs> class concat_range { |
916 | public: |
917 | using iterator = |
918 | concat_iterator<ValueT, |
919 | decltype(std::begin(std::declval<RangeTs &>()))...>; |
920 | |
921 | private: |
922 | std::tuple<RangeTs...> Ranges; |
923 | |
924 | template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) { |
925 | return iterator(std::get<Ns>(Ranges)...); |
926 | } |
927 | template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) { |
928 | return iterator(make_range(std::end(std::get<Ns>(Ranges)), |
929 | std::end(std::get<Ns>(Ranges)))...); |
930 | } |
931 | |
932 | public: |
933 | concat_range(RangeTs &&... Ranges) |
934 | : Ranges(std::forward<RangeTs>(Ranges)...) {} |
935 | |
936 | iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); } |
937 | iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); } |
938 | }; |
939 | |
940 | } // end namespace detail |
941 | |
942 | /// Concatenated range across two or more ranges. |
943 | /// |
944 | /// The desired value type must be explicitly specified. |
945 | template <typename ValueT, typename... RangeTs> |
946 | detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) { |
947 | static_assert(sizeof...(RangeTs) > 1, |
948 | "Need more than one range to concatenate!"); |
949 | return detail::concat_range<ValueT, RangeTs...>( |
950 | std::forward<RangeTs>(Ranges)...); |
951 | } |
952 | |
953 | //===----------------------------------------------------------------------===// |
954 | // Extra additions to <utility> |
955 | //===----------------------------------------------------------------------===// |
956 | |
957 | /// Function object to check whether the first component of a std::pair |
958 | /// compares less than the first component of another std::pair. |
959 | struct less_first { |
960 | template <typename T> bool operator()(const T &lhs, const T &rhs) const { |
961 | return lhs.first < rhs.first; |
962 | } |
963 | }; |
964 | |
965 | /// Function object to check whether the second component of a std::pair |
966 | /// compares less than the second component of another std::pair. |
967 | struct less_second { |
968 | template <typename T> bool operator()(const T &lhs, const T &rhs) const { |
969 | return lhs.second < rhs.second; |
970 | } |
971 | }; |
972 | |
973 | /// \brief Function object to apply a binary function to the first component of |
974 | /// a std::pair. |
975 | template<typename FuncTy> |
976 | struct on_first { |
977 | FuncTy func; |
978 | |
979 | template <typename T> |
980 | auto operator()(const T &lhs, const T &rhs) const |
981 | -> decltype(func(lhs.first, rhs.first)) { |
982 | return func(lhs.first, rhs.first); |
983 | } |
984 | }; |
985 | |
986 | // A subset of N3658. More stuff can be added as-needed. |
987 | |
988 | /// Represents a compile-time sequence of integers. |
989 | template <class T, T... I> struct integer_sequence { |
990 | using value_type = T; |
991 | |
992 | static constexpr size_t size() { return sizeof...(I); } |
993 | }; |
994 | |
995 | /// Alias for the common case of a sequence of size_ts. |
996 | template <size_t... I> |
997 | struct index_sequence : integer_sequence<std::size_t, I...> {}; |
998 | |
999 | template <std::size_t N, std::size_t... I> |
1000 | struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {}; |
1001 | template <std::size_t... I> |
1002 | struct build_index_impl<0, I...> : index_sequence<I...> {}; |
1003 | |
1004 | /// Creates a compile-time integer sequence for a parameter pack. |
1005 | template <class... Ts> |
1006 | struct index_sequence_for : build_index_impl<sizeof...(Ts)> {}; |
1007 | |
1008 | /// Utility type to build an inheritance chain that makes it easy to rank |
1009 | /// overload candidates. |
1010 | template <int N> struct rank : rank<N - 1> {}; |
1011 | template <> struct rank<0> {}; |
1012 | |
1013 | /// traits class for checking whether type T is one of any of the given |
1014 | /// types in the variadic list. |
1015 | template <typename T, typename... Ts> struct is_one_of { |
1016 | static const bool value = false; |
1017 | }; |
1018 | |
1019 | template <typename T, typename U, typename... Ts> |
1020 | struct is_one_of<T, U, Ts...> { |
1021 | static const bool value = |
1022 | std::is_same<T, U>::value || is_one_of<T, Ts...>::value; |
1023 | }; |
1024 | |
1025 | /// traits class for checking whether type T is a base class for all |
1026 | /// the given types in the variadic list. |
1027 | template <typename T, typename... Ts> struct are_base_of { |
1028 | static const bool value = true; |
1029 | }; |
1030 | |
1031 | template <typename T, typename U, typename... Ts> |
1032 | struct are_base_of<T, U, Ts...> { |
1033 | static const bool value = |
1034 | std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value; |
1035 | }; |
1036 | |
1037 | //===----------------------------------------------------------------------===// |
1038 | // Extra additions for arrays |
1039 | //===----------------------------------------------------------------------===// |
1040 | |
1041 | /// Find the length of an array. |
1042 | template <class T, std::size_t N> |
1043 | constexpr inline size_t array_lengthof(T (&)[N]) { |
1044 | return N; |
1045 | } |
1046 | |
1047 | /// Adapt std::less<T> for array_pod_sort. |
1048 | template<typename T> |
1049 | inline int array_pod_sort_comparator(const void *P1, const void *P2) { |
1050 | if (std::less<T>()(*reinterpret_cast<const T*>(P1), |
1051 | *reinterpret_cast<const T*>(P2))) |
1052 | return -1; |
1053 | if (std::less<T>()(*reinterpret_cast<const T*>(P2), |
1054 | *reinterpret_cast<const T*>(P1))) |
1055 | return 1; |
1056 | return 0; |
1057 | } |
1058 | |
1059 | /// get_array_pod_sort_comparator - This is an internal helper function used to |
1060 | /// get type deduction of T right. |
1061 | template<typename T> |
1062 | inline int (*get_array_pod_sort_comparator(const T &)) |
1063 | (const void*, const void*) { |
1064 | return array_pod_sort_comparator<T>; |
1065 | } |
1066 | |
1067 | /// array_pod_sort - This sorts an array with the specified start and end |
1068 | /// extent. This is just like std::sort, except that it calls qsort instead of |
1069 | /// using an inlined template. qsort is slightly slower than std::sort, but |
1070 | /// most sorts are not performance critical in LLVM and std::sort has to be |
1071 | /// template instantiated for each type, leading to significant measured code |
1072 | /// bloat. This function should generally be used instead of std::sort where |
1073 | /// possible. |
1074 | /// |
1075 | /// This function assumes that you have simple POD-like types that can be |
1076 | /// compared with std::less and can be moved with memcpy. If this isn't true, |
1077 | /// you should use std::sort. |
1078 | /// |
1079 | /// NOTE: If qsort_r were portable, we could allow a custom comparator and |
1080 | /// default to std::less. |
1081 | template<class IteratorTy> |
1082 | inline void array_pod_sort(IteratorTy Start, IteratorTy End) { |
1083 | // Don't inefficiently call qsort with one element or trigger undefined |
1084 | // behavior with an empty sequence. |
1085 | auto NElts = End - Start; |
1086 | if (NElts <= 1) return; |
1087 | #ifdef EXPENSIVE_CHECKS |
1088 | std::mt19937 Generator(std::random_device{}()); |
1089 | std::shuffle(Start, End, Generator); |
1090 | #endif |
1091 | qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start)); |
1092 | } |
1093 | |
1094 | template <class IteratorTy> |
1095 | inline void array_pod_sort( |
1096 | IteratorTy Start, IteratorTy End, |
1097 | int (*Compare)( |
1098 | const typename std::iterator_traits<IteratorTy>::value_type *, |
1099 | const typename std::iterator_traits<IteratorTy>::value_type *)) { |
1100 | // Don't inefficiently call qsort with one element or trigger undefined |
1101 | // behavior with an empty sequence. |
1102 | auto NElts = End - Start; |
1103 | if (NElts <= 1) return; |
1104 | #ifdef EXPENSIVE_CHECKS |
1105 | std::mt19937 Generator(std::random_device{}()); |
1106 | std::shuffle(Start, End, Generator); |
1107 | #endif |
1108 | qsort(&*Start, NElts, sizeof(*Start), |
1109 | reinterpret_cast<int (*)(const void *, const void *)>(Compare)); |
1110 | } |
1111 | |
1112 | // Provide wrappers to std::sort which shuffle the elements before sorting |
1113 | // to help uncover non-deterministic behavior (PR35135). |
1114 | template <typename IteratorTy> |
1115 | inline void sort(IteratorTy Start, IteratorTy End) { |
1116 | #ifdef EXPENSIVE_CHECKS |
1117 | std::mt19937 Generator(std::random_device{}()); |
1118 | std::shuffle(Start, End, Generator); |
1119 | #endif |
1120 | std::sort(Start, End); |
1121 | } |
1122 | |
1123 | template <typename Container> inline void sort(Container &&C) { |
1124 | llvm::sort(adl_begin(C), adl_end(C)); |
1125 | } |
1126 | |
1127 | template <typename IteratorTy, typename Compare> |
1128 | inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) { |
1129 | #ifdef EXPENSIVE_CHECKS |
1130 | std::mt19937 Generator(std::random_device{}()); |
1131 | std::shuffle(Start, End, Generator); |
1132 | #endif |
1133 | std::sort(Start, End, Comp); |
1134 | } |
1135 | |
1136 | template <typename Container, typename Compare> |
1137 | inline void sort(Container &&C, Compare Comp) { |
1138 | llvm::sort(adl_begin(C), adl_end(C), Comp); |
1139 | } |
1140 | |
1141 | //===----------------------------------------------------------------------===// |
1142 | // Extra additions to <algorithm> |
1143 | //===----------------------------------------------------------------------===// |
1144 | |
1145 | /// For a container of pointers, deletes the pointers and then clears the |
1146 | /// container. |
1147 | template<typename Container> |
1148 | void DeleteContainerPointers(Container &C) { |
1149 | for (auto V : C) |
1150 | delete V; |
1151 | C.clear(); |
1152 | } |
1153 | |
1154 | /// In a container of pairs (usually a map) whose second element is a pointer, |
1155 | /// deletes the second elements and then clears the container. |
1156 | template<typename Container> |
1157 | void DeleteContainerSeconds(Container &C) { |
1158 | for (auto &V : C) |
1159 | delete V.second; |
1160 | C.clear(); |
1161 | } |
1162 | |
1163 | /// Get the size of a range. This is a wrapper function around std::distance |
1164 | /// which is only enabled when the operation is O(1). |
1165 | template <typename R> |
1166 | auto size(R &&Range, typename std::enable_if< |
1167 | std::is_same<typename std::iterator_traits<decltype( |
1168 | Range.begin())>::iterator_category, |
1169 | std::random_access_iterator_tag>::value, |
1170 | void>::type * = nullptr) |
1171 | -> decltype(std::distance(Range.begin(), Range.end())) { |
1172 | return std::distance(Range.begin(), Range.end()); |
1173 | } |
1174 | |
1175 | /// Provide wrappers to std::for_each which take ranges instead of having to |
1176 | /// pass begin/end explicitly. |
1177 | template <typename R, typename UnaryPredicate> |
1178 | UnaryPredicate for_each(R &&Range, UnaryPredicate P) { |
1179 | return std::for_each(adl_begin(Range), adl_end(Range), P); |
1180 | } |
1181 | |
1182 | /// Provide wrappers to std::all_of which take ranges instead of having to pass |
1183 | /// begin/end explicitly. |
1184 | template <typename R, typename UnaryPredicate> |
1185 | bool all_of(R &&Range, UnaryPredicate P) { |
1186 | return std::all_of(adl_begin(Range), adl_end(Range), P); |
1187 | } |
1188 | |
1189 | /// Provide wrappers to std::any_of which take ranges instead of having to pass |
1190 | /// begin/end explicitly. |
1191 | template <typename R, typename UnaryPredicate> |
1192 | bool any_of(R &&Range, UnaryPredicate P) { |
1193 | return std::any_of(adl_begin(Range), adl_end(Range), P); |
1194 | } |
1195 | |
1196 | /// Provide wrappers to std::none_of which take ranges instead of having to pass |
1197 | /// begin/end explicitly. |
1198 | template <typename R, typename UnaryPredicate> |
1199 | bool none_of(R &&Range, UnaryPredicate P) { |
1200 | return std::none_of(adl_begin(Range), adl_end(Range), P); |
1201 | } |
1202 | |
1203 | /// Provide wrappers to std::find which take ranges instead of having to pass |
1204 | /// begin/end explicitly. |
1205 | template <typename R, typename T> |
1206 | auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) { |
1207 | return std::find(adl_begin(Range), adl_end(Range), Val); |
1208 | } |
1209 | |
1210 | /// Provide wrappers to std::find_if which take ranges instead of having to pass |
1211 | /// begin/end explicitly. |
1212 | template <typename R, typename UnaryPredicate> |
1213 | auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
1214 | return std::find_if(adl_begin(Range), adl_end(Range), P); |
1215 | } |
1216 | |
1217 | template <typename R, typename UnaryPredicate> |
1218 | auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
1219 | return std::find_if_not(adl_begin(Range), adl_end(Range), P); |
1220 | } |
1221 | |
1222 | /// Provide wrappers to std::remove_if which take ranges instead of having to |
1223 | /// pass begin/end explicitly. |
1224 | template <typename R, typename UnaryPredicate> |
1225 | auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
1226 | return std::remove_if(adl_begin(Range), adl_end(Range), P); |
1227 | } |
1228 | |
1229 | /// Provide wrappers to std::copy_if which take ranges instead of having to |
1230 | /// pass begin/end explicitly. |
1231 | template <typename R, typename OutputIt, typename UnaryPredicate> |
1232 | OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) { |
1233 | return std::copy_if(adl_begin(Range), adl_end(Range), Out, P); |
1234 | } |
1235 | |
1236 | template <typename R, typename OutputIt> |
1237 | OutputIt copy(R &&Range, OutputIt Out) { |
1238 | return std::copy(adl_begin(Range), adl_end(Range), Out); |
1239 | } |
1240 | |
1241 | /// Wrapper function around std::find to detect if an element exists |
1242 | /// in a container. |
1243 | template <typename R, typename E> |
1244 | bool is_contained(R &&Range, const E &Element) { |
1245 | return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range); |
1246 | } |
1247 | |
1248 | /// Wrapper function around std::count to count the number of times an element |
1249 | /// \p Element occurs in the given range \p Range. |
1250 | template <typename R, typename E> |
1251 | auto count(R &&Range, const E &Element) -> |
1252 | typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type { |
1253 | return std::count(adl_begin(Range), adl_end(Range), Element); |
1254 | } |
1255 | |
1256 | /// Wrapper function around std::count_if to count the number of times an |
1257 | /// element satisfying a given predicate occurs in a range. |
1258 | template <typename R, typename UnaryPredicate> |
1259 | auto count_if(R &&Range, UnaryPredicate P) -> |
1260 | typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type { |
1261 | return std::count_if(adl_begin(Range), adl_end(Range), P); |
1262 | } |
1263 | |
1264 | /// Wrapper function around std::transform to apply a function to a range and |
1265 | /// store the result elsewhere. |
1266 | template <typename R, typename OutputIt, typename UnaryPredicate> |
1267 | OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) { |
1268 | return std::transform(adl_begin(Range), adl_end(Range), d_first, P); |
1269 | } |
1270 | |
1271 | /// Provide wrappers to std::partition which take ranges instead of having to |
1272 | /// pass begin/end explicitly. |
1273 | template <typename R, typename UnaryPredicate> |
1274 | auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) { |
1275 | return std::partition(adl_begin(Range), adl_end(Range), P); |
1276 | } |
1277 | |
1278 | /// Provide wrappers to std::lower_bound which take ranges instead of having to |
1279 | /// pass begin/end explicitly. |
1280 | template <typename R, typename T> |
1281 | auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range)) { |
1282 | return std::lower_bound(adl_begin(Range), adl_end(Range), |
1283 | std::forward<T>(Value)); |
1284 | } |
1285 | |
1286 | template <typename R, typename T, typename Compare> |
1287 | auto lower_bound(R &&Range, T &&Value, Compare C) |
1288 | -> decltype(adl_begin(Range)) { |
1289 | return std::lower_bound(adl_begin(Range), adl_end(Range), |
1290 | std::forward<T>(Value), C); |
1291 | } |
1292 | |
1293 | /// Provide wrappers to std::upper_bound which take ranges instead of having to |
1294 | /// pass begin/end explicitly. |
1295 | template <typename R, typename T> |
1296 | auto upper_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range)) { |
1297 | return std::upper_bound(adl_begin(Range), adl_end(Range), |
1298 | std::forward<T>(Value)); |
1299 | } |
1300 | |
1301 | template <typename R, typename T, typename Compare> |
1302 | auto upper_bound(R &&Range, T &&Value, Compare C) |
1303 | -> decltype(adl_begin(Range)) { |
1304 | return std::upper_bound(adl_begin(Range), adl_end(Range), |
1305 | std::forward<T>(Value), C); |
1306 | } |
1307 | |
1308 | template <typename R> |
1309 | void stable_sort(R &&Range) { |
1310 | std::stable_sort(adl_begin(Range), adl_end(Range)); |
1311 | } |
1312 | |
1313 | template <typename R, typename Compare> |
1314 | void stable_sort(R &&Range, Compare C) { |
1315 | std::stable_sort(adl_begin(Range), adl_end(Range), C); |
1316 | } |
1317 | |
1318 | /// Binary search for the first index where a predicate is true. |
1319 | /// Returns the first I in [Lo, Hi) where C(I) is true, or Hi if it never is. |
1320 | /// Requires that C is always false below some limit, and always true above it. |
1321 | /// |
1322 | /// Example: |
1323 | /// size_t DawnModernEra = bsearch(1776, 2050, [](size_t Year){ |
1324 | /// return Presidents.for(Year).twitterHandle() != None; |
1325 | /// }); |
1326 | /// |
1327 | /// Note the return value differs from std::binary_search! |
1328 | template <typename Predicate> |
1329 | size_t bsearch(size_t Lo, size_t Hi, Predicate P) { |
1330 | while (Lo != Hi) { |
1331 | assert(Hi > Lo)((Hi > Lo) ? static_cast<void> (0) : __assert_fail ( "Hi > Lo", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 1331, __PRETTY_FUNCTION__)); |
1332 | size_t Mid = Lo + (Hi - Lo) / 2; |
1333 | if (P(Mid)) |
1334 | Hi = Mid; |
1335 | else |
1336 | Lo = Mid + 1; |
1337 | } |
1338 | return Hi; |
1339 | } |
1340 | |
1341 | /// Binary search for the first iterator where a predicate is true. |
1342 | /// Returns the first I in [Lo, Hi) where C(*I) is true, or Hi if it never is. |
1343 | /// Requires that C is always false below some limit, and always true above it. |
1344 | template <typename It, typename Predicate, |
1345 | typename Val = decltype(*std::declval<It>())> |
1346 | It bsearch(It Lo, It Hi, Predicate P) { |
1347 | return std::lower_bound(Lo, Hi, 0u, |
1348 | [&](const Val &V, unsigned) { return !P(V); }); |
1349 | } |
1350 | |
1351 | /// Binary search for the first iterator in a range where a predicate is true. |
1352 | /// Requires that C is always false below some limit, and always true above it. |
1353 | template <typename R, typename Predicate> |
1354 | auto bsearch(R &&Range, Predicate P) -> decltype(adl_begin(Range)) { |
1355 | return bsearch(adl_begin(Range), adl_end(Range), P); |
1356 | } |
1357 | |
1358 | /// Wrapper function around std::equal to detect if all elements |
1359 | /// in a container are same. |
1360 | template <typename R> |
1361 | bool is_splat(R &&Range) { |
1362 | size_t range_size = size(Range); |
1363 | return range_size != 0 && (range_size == 1 || |
1364 | std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range))); |
1365 | } |
1366 | |
1367 | /// Given a range of type R, iterate the entire range and return a |
1368 | /// SmallVector with elements of the vector. This is useful, for example, |
1369 | /// when you want to iterate a range and then sort the results. |
1370 | template <unsigned Size, typename R> |
1371 | SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size> |
1372 | to_vector(R &&Range) { |
1373 | return {adl_begin(Range), adl_end(Range)}; |
1374 | } |
1375 | |
1376 | /// Provide a container algorithm similar to C++ Library Fundamentals v2's |
1377 | /// `erase_if` which is equivalent to: |
1378 | /// |
1379 | /// C.erase(remove_if(C, pred), C.end()); |
1380 | /// |
1381 | /// This version works for any container with an erase method call accepting |
1382 | /// two iterators. |
1383 | template <typename Container, typename UnaryPredicate> |
1384 | void erase_if(Container &C, UnaryPredicate P) { |
1385 | C.erase(remove_if(C, P), C.end()); |
1386 | } |
1387 | |
1388 | //===----------------------------------------------------------------------===// |
1389 | // Extra additions to <memory> |
1390 | //===----------------------------------------------------------------------===// |
1391 | |
1392 | // Implement make_unique according to N3656. |
1393 | |
1394 | /// Constructs a `new T()` with the given args and returns a |
1395 | /// `unique_ptr<T>` which owns the object. |
1396 | /// |
1397 | /// Example: |
1398 | /// |
1399 | /// auto p = make_unique<int>(); |
1400 | /// auto p = make_unique<std::tuple<int, int>>(0, 1); |
1401 | template <class T, class... Args> |
1402 | typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type |
1403 | make_unique(Args &&... args) { |
1404 | return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); |
1405 | } |
1406 | |
1407 | /// Constructs a `new T[n]` with the given args and returns a |
1408 | /// `unique_ptr<T[]>` which owns the object. |
1409 | /// |
1410 | /// \param n size of the new array. |
1411 | /// |
1412 | /// Example: |
1413 | /// |
1414 | /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's. |
1415 | template <class T> |
1416 | typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0, |
1417 | std::unique_ptr<T>>::type |
1418 | make_unique(size_t n) { |
1419 | return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]()); |
1420 | } |
1421 | |
1422 | /// This function isn't used and is only here to provide better compile errors. |
1423 | template <class T, class... Args> |
1424 | typename std::enable_if<std::extent<T>::value != 0>::type |
1425 | make_unique(Args &&...) = delete; |
1426 | |
1427 | struct FreeDeleter { |
1428 | void operator()(void* v) { |
1429 | ::free(v); |
1430 | } |
1431 | }; |
1432 | |
1433 | template<typename First, typename Second> |
1434 | struct pair_hash { |
1435 | size_t operator()(const std::pair<First, Second> &P) const { |
1436 | return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second); |
1437 | } |
1438 | }; |
1439 | |
1440 | /// A functor like C++14's std::less<void> in its absence. |
1441 | struct less { |
1442 | template <typename A, typename B> bool operator()(A &&a, B &&b) const { |
1443 | return std::forward<A>(a) < std::forward<B>(b); |
1444 | } |
1445 | }; |
1446 | |
1447 | /// A functor like C++14's std::equal<void> in its absence. |
1448 | struct equal { |
1449 | template <typename A, typename B> bool operator()(A &&a, B &&b) const { |
1450 | return std::forward<A>(a) == std::forward<B>(b); |
1451 | } |
1452 | }; |
1453 | |
1454 | /// Binary functor that adapts to any other binary functor after dereferencing |
1455 | /// operands. |
1456 | template <typename T> struct deref { |
1457 | T func; |
1458 | |
1459 | // Could be further improved to cope with non-derivable functors and |
1460 | // non-binary functors (should be a variadic template member function |
1461 | // operator()). |
1462 | template <typename A, typename B> |
1463 | auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) { |
1464 | assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 1464, __PRETTY_FUNCTION__)); |
1465 | assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 1465, __PRETTY_FUNCTION__)); |
1466 | return func(*lhs, *rhs); |
1467 | } |
1468 | }; |
1469 | |
1470 | namespace detail { |
1471 | |
1472 | template <typename R> class enumerator_iter; |
1473 | |
1474 | template <typename R> struct result_pair { |
1475 | friend class enumerator_iter<R>; |
1476 | |
1477 | result_pair() = default; |
1478 | result_pair(std::size_t Index, IterOfRange<R> Iter) |
1479 | : Index(Index), Iter(Iter) {} |
1480 | |
1481 | result_pair<R> &operator=(const result_pair<R> &Other) { |
1482 | Index = Other.Index; |
1483 | Iter = Other.Iter; |
1484 | return *this; |
1485 | } |
1486 | |
1487 | std::size_t index() const { return Index; } |
1488 | const ValueOfRange<R> &value() const { return *Iter; } |
1489 | ValueOfRange<R> &value() { return *Iter; } |
1490 | |
1491 | private: |
1492 | std::size_t Index = std::numeric_limits<std::size_t>::max(); |
1493 | IterOfRange<R> Iter; |
1494 | }; |
1495 | |
1496 | template <typename R> |
1497 | class enumerator_iter |
1498 | : public iterator_facade_base< |
1499 | enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>, |
1500 | typename std::iterator_traits<IterOfRange<R>>::difference_type, |
1501 | typename std::iterator_traits<IterOfRange<R>>::pointer, |
1502 | typename std::iterator_traits<IterOfRange<R>>::reference> { |
1503 | using result_type = result_pair<R>; |
1504 | |
1505 | public: |
1506 | explicit enumerator_iter(IterOfRange<R> EndIter) |
1507 | : Result(std::numeric_limits<size_t>::max(), EndIter) {} |
1508 | |
1509 | enumerator_iter(std::size_t Index, IterOfRange<R> Iter) |
1510 | : Result(Index, Iter) {} |
1511 | |
1512 | result_type &operator*() { return Result; } |
1513 | const result_type &operator*() const { return Result; } |
1514 | |
1515 | enumerator_iter<R> &operator++() { |
1516 | assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ? static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/STLExtras.h" , 1516, __PRETTY_FUNCTION__)); |
1517 | ++Result.Iter; |
1518 | ++Result.Index; |
1519 | return *this; |
1520 | } |
1521 | |
1522 | bool operator==(const enumerator_iter<R> &RHS) const { |
1523 | // Don't compare indices here, only iterators. It's possible for an end |
1524 | // iterator to have different indices depending on whether it was created |
1525 | // by calling std::end() versus incrementing a valid iterator. |
1526 | return Result.Iter == RHS.Result.Iter; |
1527 | } |
1528 | |
1529 | enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) { |
1530 | Result = Other.Result; |
1531 | return *this; |
1532 | } |
1533 | |
1534 | private: |
1535 | result_type Result; |
1536 | }; |
1537 | |
1538 | template <typename R> class enumerator { |
1539 | public: |
1540 | explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {} |
1541 | |
1542 | enumerator_iter<R> begin() { |
1543 | return enumerator_iter<R>(0, std::begin(TheRange)); |
1544 | } |
1545 | |
1546 | enumerator_iter<R> end() { |
1547 | return enumerator_iter<R>(std::end(TheRange)); |
1548 | } |
1549 | |
1550 | private: |
1551 | R TheRange; |
1552 | }; |
1553 | |
1554 | } // end namespace detail |
1555 | |
1556 | /// Given an input range, returns a new range whose values are are pair (A,B) |
1557 | /// such that A is the 0-based index of the item in the sequence, and B is |
1558 | /// the value from the original sequence. Example: |
1559 | /// |
1560 | /// std::vector<char> Items = {'A', 'B', 'C', 'D'}; |
1561 | /// for (auto X : enumerate(Items)) { |
1562 | /// printf("Item %d - %c\n", X.index(), X.value()); |
1563 | /// } |
1564 | /// |
1565 | /// Output: |
1566 | /// Item 0 - A |
1567 | /// Item 1 - B |
1568 | /// Item 2 - C |
1569 | /// Item 3 - D |
1570 | /// |
1571 | template <typename R> detail::enumerator<R> enumerate(R &&TheRange) { |
1572 | return detail::enumerator<R>(std::forward<R>(TheRange)); |
1573 | } |
1574 | |
1575 | namespace detail { |
1576 | |
1577 | template <typename F, typename Tuple, std::size_t... I> |
1578 | auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>) |
1579 | -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) { |
1580 | return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); |
1581 | } |
1582 | |
1583 | } // end namespace detail |
1584 | |
1585 | /// Given an input tuple (a1, a2, ..., an), pass the arguments of the |
1586 | /// tuple variadically to f as if by calling f(a1, a2, ..., an) and |
1587 | /// return the result. |
1588 | template <typename F, typename Tuple> |
1589 | auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl( |
1590 | std::forward<F>(f), std::forward<Tuple>(t), |
1591 | build_index_impl< |
1592 | std::tuple_size<typename std::decay<Tuple>::type>::value>{})) { |
1593 | using Indices = build_index_impl< |
1594 | std::tuple_size<typename std::decay<Tuple>::type>::value>; |
1595 | |
1596 | return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t), |
1597 | Indices{}); |
1598 | } |
1599 | |
1600 | /// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N) |
1601 | /// time. Not meant for use with random-access iterators. |
1602 | template <typename IterTy> |
1603 | bool hasNItems( |
1604 | IterTy &&Begin, IterTy &&End, unsigned N, |
1605 | typename std::enable_if< |
1606 | !std::is_same< |
1607 | typename std::iterator_traits<typename std::remove_reference< |
1608 | decltype(Begin)>::type>::iterator_category, |
1609 | std::random_access_iterator_tag>::value, |
1610 | void>::type * = nullptr) { |
1611 | for (; N; --N, ++Begin) |
1612 | if (Begin == End) |
1613 | return false; // Too few. |
1614 | return Begin == End; |
1615 | } |
1616 | |
1617 | /// Return true if the sequence [Begin, End) has N or more items. Runs in O(N) |
1618 | /// time. Not meant for use with random-access iterators. |
1619 | template <typename IterTy> |
1620 | bool hasNItemsOrMore( |
1621 | IterTy &&Begin, IterTy &&End, unsigned N, |
1622 | typename std::enable_if< |
1623 | !std::is_same< |
1624 | typename std::iterator_traits<typename std::remove_reference< |
1625 | decltype(Begin)>::type>::iterator_category, |
1626 | std::random_access_iterator_tag>::value, |
1627 | void>::type * = nullptr) { |
1628 | for (; N; --N, ++Begin) |
1629 | if (Begin == End) |
1630 | return false; // Too few. |
1631 | return true; |
1632 | } |
1633 | |
1634 | /// Returns a raw pointer that represents the same address as the argument. |
1635 | /// |
1636 | /// The late bound return should be removed once we move to C++14 to better |
1637 | /// align with the C++20 declaration. Also, this implementation can be removed |
1638 | /// once we move to C++20 where it's defined as std::to_addres() |
1639 | /// |
1640 | /// The std::pointer_traits<>::to_address(p) variations of these overloads has |
1641 | /// not been implemented. |
1642 | template <class Ptr> auto to_address(const Ptr &P) -> decltype(P.operator->()) { |
1643 | return P.operator->(); |
1644 | } |
1645 | template <class T> constexpr T *to_address(T *P) { return P; } |
1646 | |
1647 | } // end namespace llvm |
1648 | |
1649 | #endif // LLVM_ADT_STLEXTRAS_H |