clang API Documentation
00001 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements type-related semantic analysis. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/SemaInternal.h" 00015 #include "TypeLocBuilder.h" 00016 #include "clang/AST/ASTConsumer.h" 00017 #include "clang/AST/ASTContext.h" 00018 #include "clang/AST/ASTMutationListener.h" 00019 #include "clang/AST/CXXInheritance.h" 00020 #include "clang/AST/DeclObjC.h" 00021 #include "clang/AST/DeclTemplate.h" 00022 #include "clang/AST/Expr.h" 00023 #include "clang/AST/TypeLoc.h" 00024 #include "clang/AST/TypeLocVisitor.h" 00025 #include "clang/Basic/PartialDiagnostic.h" 00026 #include "clang/Basic/TargetInfo.h" 00027 #include "clang/Parse/ParseDiagnostic.h" 00028 #include "clang/Sema/DeclSpec.h" 00029 #include "clang/Sema/DelayedDiagnostic.h" 00030 #include "clang/Sema/Lookup.h" 00031 #include "clang/Sema/ScopeInfo.h" 00032 #include "clang/Sema/Template.h" 00033 #include "llvm/ADT/SmallPtrSet.h" 00034 #include "llvm/ADT/SmallString.h" 00035 #include "llvm/Support/ErrorHandling.h" 00036 00037 using namespace clang; 00038 00039 enum TypeDiagSelector { 00040 TDS_Function, 00041 TDS_Pointer, 00042 TDS_ObjCObjOrBlock 00043 }; 00044 00045 /// isOmittedBlockReturnType - Return true if this declarator is missing a 00046 /// return type because this is a omitted return type on a block literal. 00047 static bool isOmittedBlockReturnType(const Declarator &D) { 00048 if (D.getContext() != Declarator::BlockLiteralContext || 00049 D.getDeclSpec().hasTypeSpecifier()) 00050 return false; 00051 00052 if (D.getNumTypeObjects() == 0) 00053 return true; // ^{ ... } 00054 00055 if (D.getNumTypeObjects() == 1 && 00056 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 00057 return true; // ^(int X, float Y) { ... } 00058 00059 return false; 00060 } 00061 00062 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 00063 /// doesn't apply to the given type. 00064 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 00065 QualType type) { 00066 TypeDiagSelector WhichType; 00067 bool useExpansionLoc = true; 00068 switch (attr.getKind()) { 00069 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break; 00070 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break; 00071 default: 00072 // Assume everything else was a function attribute. 00073 WhichType = TDS_Function; 00074 useExpansionLoc = false; 00075 break; 00076 } 00077 00078 SourceLocation loc = attr.getLoc(); 00079 StringRef name = attr.getName()->getName(); 00080 00081 // The GC attributes are usually written with macros; special-case them. 00082 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident 00083 : nullptr; 00084 if (useExpansionLoc && loc.isMacroID() && II) { 00085 if (II->isStr("strong")) { 00086 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 00087 } else if (II->isStr("weak")) { 00088 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 00089 } 00090 } 00091 00092 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType 00093 << type; 00094 } 00095 00096 // objc_gc applies to Objective-C pointers or, otherwise, to the 00097 // smallest available pointer type (i.e. 'void*' in 'void**'). 00098 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 00099 case AttributeList::AT_ObjCGC: \ 00100 case AttributeList::AT_ObjCOwnership 00101 00102 // Function type attributes. 00103 #define FUNCTION_TYPE_ATTRS_CASELIST \ 00104 case AttributeList::AT_NoReturn: \ 00105 case AttributeList::AT_CDecl: \ 00106 case AttributeList::AT_FastCall: \ 00107 case AttributeList::AT_StdCall: \ 00108 case AttributeList::AT_ThisCall: \ 00109 case AttributeList::AT_Pascal: \ 00110 case AttributeList::AT_VectorCall: \ 00111 case AttributeList::AT_MSABI: \ 00112 case AttributeList::AT_SysVABI: \ 00113 case AttributeList::AT_Regparm: \ 00114 case AttributeList::AT_Pcs: \ 00115 case AttributeList::AT_PnaclCall: \ 00116 case AttributeList::AT_IntelOclBicc 00117 00118 // Microsoft-specific type qualifiers. 00119 #define MS_TYPE_ATTRS_CASELIST \ 00120 case AttributeList::AT_Ptr32: \ 00121 case AttributeList::AT_Ptr64: \ 00122 case AttributeList::AT_SPtr: \ 00123 case AttributeList::AT_UPtr 00124 00125 namespace { 00126 /// An object which stores processing state for the entire 00127 /// GetTypeForDeclarator process. 00128 class TypeProcessingState { 00129 Sema &sema; 00130 00131 /// The declarator being processed. 00132 Declarator &declarator; 00133 00134 /// The index of the declarator chunk we're currently processing. 00135 /// May be the total number of valid chunks, indicating the 00136 /// DeclSpec. 00137 unsigned chunkIndex; 00138 00139 /// Whether there are non-trivial modifications to the decl spec. 00140 bool trivial; 00141 00142 /// Whether we saved the attributes in the decl spec. 00143 bool hasSavedAttrs; 00144 00145 /// The original set of attributes on the DeclSpec. 00146 SmallVector<AttributeList*, 2> savedAttrs; 00147 00148 /// A list of attributes to diagnose the uselessness of when the 00149 /// processing is complete. 00150 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 00151 00152 public: 00153 TypeProcessingState(Sema &sema, Declarator &declarator) 00154 : sema(sema), declarator(declarator), 00155 chunkIndex(declarator.getNumTypeObjects()), 00156 trivial(true), hasSavedAttrs(false) {} 00157 00158 Sema &getSema() const { 00159 return sema; 00160 } 00161 00162 Declarator &getDeclarator() const { 00163 return declarator; 00164 } 00165 00166 bool isProcessingDeclSpec() const { 00167 return chunkIndex == declarator.getNumTypeObjects(); 00168 } 00169 00170 unsigned getCurrentChunkIndex() const { 00171 return chunkIndex; 00172 } 00173 00174 void setCurrentChunkIndex(unsigned idx) { 00175 assert(idx <= declarator.getNumTypeObjects()); 00176 chunkIndex = idx; 00177 } 00178 00179 AttributeList *&getCurrentAttrListRef() const { 00180 if (isProcessingDeclSpec()) 00181 return getMutableDeclSpec().getAttributes().getListRef(); 00182 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 00183 } 00184 00185 /// Save the current set of attributes on the DeclSpec. 00186 void saveDeclSpecAttrs() { 00187 // Don't try to save them multiple times. 00188 if (hasSavedAttrs) return; 00189 00190 DeclSpec &spec = getMutableDeclSpec(); 00191 for (AttributeList *attr = spec.getAttributes().getList(); attr; 00192 attr = attr->getNext()) 00193 savedAttrs.push_back(attr); 00194 trivial &= savedAttrs.empty(); 00195 hasSavedAttrs = true; 00196 } 00197 00198 /// Record that we had nowhere to put the given type attribute. 00199 /// We will diagnose such attributes later. 00200 void addIgnoredTypeAttr(AttributeList &attr) { 00201 ignoredTypeAttrs.push_back(&attr); 00202 } 00203 00204 /// Diagnose all the ignored type attributes, given that the 00205 /// declarator worked out to the given type. 00206 void diagnoseIgnoredTypeAttrs(QualType type) const { 00207 for (SmallVectorImpl<AttributeList*>::const_iterator 00208 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 00209 i != e; ++i) 00210 diagnoseBadTypeAttribute(getSema(), **i, type); 00211 } 00212 00213 ~TypeProcessingState() { 00214 if (trivial) return; 00215 00216 restoreDeclSpecAttrs(); 00217 } 00218 00219 private: 00220 DeclSpec &getMutableDeclSpec() const { 00221 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 00222 } 00223 00224 void restoreDeclSpecAttrs() { 00225 assert(hasSavedAttrs); 00226 00227 if (savedAttrs.empty()) { 00228 getMutableDeclSpec().getAttributes().set(nullptr); 00229 return; 00230 } 00231 00232 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 00233 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 00234 savedAttrs[i]->setNext(savedAttrs[i+1]); 00235 savedAttrs.back()->setNext(nullptr); 00236 } 00237 }; 00238 } 00239 00240 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 00241 attr.setNext(head); 00242 head = &attr; 00243 } 00244 00245 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 00246 if (head == &attr) { 00247 head = attr.getNext(); 00248 return; 00249 } 00250 00251 AttributeList *cur = head; 00252 while (true) { 00253 assert(cur && cur->getNext() && "ran out of attrs?"); 00254 if (cur->getNext() == &attr) { 00255 cur->setNext(attr.getNext()); 00256 return; 00257 } 00258 cur = cur->getNext(); 00259 } 00260 } 00261 00262 static void moveAttrFromListToList(AttributeList &attr, 00263 AttributeList *&fromList, 00264 AttributeList *&toList) { 00265 spliceAttrOutOfList(attr, fromList); 00266 spliceAttrIntoList(attr, toList); 00267 } 00268 00269 /// The location of a type attribute. 00270 enum TypeAttrLocation { 00271 /// The attribute is in the decl-specifier-seq. 00272 TAL_DeclSpec, 00273 /// The attribute is part of a DeclaratorChunk. 00274 TAL_DeclChunk, 00275 /// The attribute is immediately after the declaration's name. 00276 TAL_DeclName 00277 }; 00278 00279 static void processTypeAttrs(TypeProcessingState &state, 00280 QualType &type, TypeAttrLocation TAL, 00281 AttributeList *attrs); 00282 00283 static bool handleFunctionTypeAttr(TypeProcessingState &state, 00284 AttributeList &attr, 00285 QualType &type); 00286 00287 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, 00288 AttributeList &attr, 00289 QualType &type); 00290 00291 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 00292 AttributeList &attr, QualType &type); 00293 00294 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 00295 AttributeList &attr, QualType &type); 00296 00297 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 00298 AttributeList &attr, QualType &type) { 00299 if (attr.getKind() == AttributeList::AT_ObjCGC) 00300 return handleObjCGCTypeAttr(state, attr, type); 00301 assert(attr.getKind() == AttributeList::AT_ObjCOwnership); 00302 return handleObjCOwnershipTypeAttr(state, attr, type); 00303 } 00304 00305 /// Given the index of a declarator chunk, check whether that chunk 00306 /// directly specifies the return type of a function and, if so, find 00307 /// an appropriate place for it. 00308 /// 00309 /// \param i - a notional index which the search will start 00310 /// immediately inside 00311 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 00312 unsigned i) { 00313 assert(i <= declarator.getNumTypeObjects()); 00314 00315 DeclaratorChunk *result = nullptr; 00316 00317 // First, look inwards past parens for a function declarator. 00318 for (; i != 0; --i) { 00319 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 00320 switch (fnChunk.Kind) { 00321 case DeclaratorChunk::Paren: 00322 continue; 00323 00324 // If we find anything except a function, bail out. 00325 case DeclaratorChunk::Pointer: 00326 case DeclaratorChunk::BlockPointer: 00327 case DeclaratorChunk::Array: 00328 case DeclaratorChunk::Reference: 00329 case DeclaratorChunk::MemberPointer: 00330 return result; 00331 00332 // If we do find a function declarator, scan inwards from that, 00333 // looking for a block-pointer declarator. 00334 case DeclaratorChunk::Function: 00335 for (--i; i != 0; --i) { 00336 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1); 00337 switch (blockChunk.Kind) { 00338 case DeclaratorChunk::Paren: 00339 case DeclaratorChunk::Pointer: 00340 case DeclaratorChunk::Array: 00341 case DeclaratorChunk::Function: 00342 case DeclaratorChunk::Reference: 00343 case DeclaratorChunk::MemberPointer: 00344 continue; 00345 case DeclaratorChunk::BlockPointer: 00346 result = &blockChunk; 00347 goto continue_outer; 00348 } 00349 llvm_unreachable("bad declarator chunk kind"); 00350 } 00351 00352 // If we run out of declarators doing that, we're done. 00353 return result; 00354 } 00355 llvm_unreachable("bad declarator chunk kind"); 00356 00357 // Okay, reconsider from our new point. 00358 continue_outer: ; 00359 } 00360 00361 // Ran out of chunks, bail out. 00362 return result; 00363 } 00364 00365 /// Given that an objc_gc attribute was written somewhere on a 00366 /// declaration *other* than on the declarator itself (for which, use 00367 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 00368 /// didn't apply in whatever position it was written in, try to move 00369 /// it to a more appropriate position. 00370 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 00371 AttributeList &attr, 00372 QualType type) { 00373 Declarator &declarator = state.getDeclarator(); 00374 00375 // Move it to the outermost normal or block pointer declarator. 00376 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 00377 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 00378 switch (chunk.Kind) { 00379 case DeclaratorChunk::Pointer: 00380 case DeclaratorChunk::BlockPointer: { 00381 // But don't move an ARC ownership attribute to the return type 00382 // of a block. 00383 DeclaratorChunk *destChunk = nullptr; 00384 if (state.isProcessingDeclSpec() && 00385 attr.getKind() == AttributeList::AT_ObjCOwnership) 00386 destChunk = maybeMovePastReturnType(declarator, i - 1); 00387 if (!destChunk) destChunk = &chunk; 00388 00389 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 00390 destChunk->getAttrListRef()); 00391 return; 00392 } 00393 00394 case DeclaratorChunk::Paren: 00395 case DeclaratorChunk::Array: 00396 continue; 00397 00398 // We may be starting at the return type of a block. 00399 case DeclaratorChunk::Function: 00400 if (state.isProcessingDeclSpec() && 00401 attr.getKind() == AttributeList::AT_ObjCOwnership) { 00402 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) { 00403 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 00404 dest->getAttrListRef()); 00405 return; 00406 } 00407 } 00408 goto error; 00409 00410 // Don't walk through these. 00411 case DeclaratorChunk::Reference: 00412 case DeclaratorChunk::MemberPointer: 00413 goto error; 00414 } 00415 } 00416 error: 00417 00418 diagnoseBadTypeAttribute(state.getSema(), attr, type); 00419 } 00420 00421 /// Distribute an objc_gc type attribute that was written on the 00422 /// declarator. 00423 static void 00424 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 00425 AttributeList &attr, 00426 QualType &declSpecType) { 00427 Declarator &declarator = state.getDeclarator(); 00428 00429 // objc_gc goes on the innermost pointer to something that's not a 00430 // pointer. 00431 unsigned innermost = -1U; 00432 bool considerDeclSpec = true; 00433 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 00434 DeclaratorChunk &chunk = declarator.getTypeObject(i); 00435 switch (chunk.Kind) { 00436 case DeclaratorChunk::Pointer: 00437 case DeclaratorChunk::BlockPointer: 00438 innermost = i; 00439 continue; 00440 00441 case DeclaratorChunk::Reference: 00442 case DeclaratorChunk::MemberPointer: 00443 case DeclaratorChunk::Paren: 00444 case DeclaratorChunk::Array: 00445 continue; 00446 00447 case DeclaratorChunk::Function: 00448 considerDeclSpec = false; 00449 goto done; 00450 } 00451 } 00452 done: 00453 00454 // That might actually be the decl spec if we weren't blocked by 00455 // anything in the declarator. 00456 if (considerDeclSpec) { 00457 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 00458 // Splice the attribute into the decl spec. Prevents the 00459 // attribute from being applied multiple times and gives 00460 // the source-location-filler something to work with. 00461 state.saveDeclSpecAttrs(); 00462 moveAttrFromListToList(attr, declarator.getAttrListRef(), 00463 declarator.getMutableDeclSpec().getAttributes().getListRef()); 00464 return; 00465 } 00466 } 00467 00468 // Otherwise, if we found an appropriate chunk, splice the attribute 00469 // into it. 00470 if (innermost != -1U) { 00471 moveAttrFromListToList(attr, declarator.getAttrListRef(), 00472 declarator.getTypeObject(innermost).getAttrListRef()); 00473 return; 00474 } 00475 00476 // Otherwise, diagnose when we're done building the type. 00477 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 00478 state.addIgnoredTypeAttr(attr); 00479 } 00480 00481 /// A function type attribute was written somewhere in a declaration 00482 /// *other* than on the declarator itself or in the decl spec. Given 00483 /// that it didn't apply in whatever position it was written in, try 00484 /// to move it to a more appropriate position. 00485 static void distributeFunctionTypeAttr(TypeProcessingState &state, 00486 AttributeList &attr, 00487 QualType type) { 00488 Declarator &declarator = state.getDeclarator(); 00489 00490 // Try to push the attribute from the return type of a function to 00491 // the function itself. 00492 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 00493 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 00494 switch (chunk.Kind) { 00495 case DeclaratorChunk::Function: 00496 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 00497 chunk.getAttrListRef()); 00498 return; 00499 00500 case DeclaratorChunk::Paren: 00501 case DeclaratorChunk::Pointer: 00502 case DeclaratorChunk::BlockPointer: 00503 case DeclaratorChunk::Array: 00504 case DeclaratorChunk::Reference: 00505 case DeclaratorChunk::MemberPointer: 00506 continue; 00507 } 00508 } 00509 00510 diagnoseBadTypeAttribute(state.getSema(), attr, type); 00511 } 00512 00513 /// Try to distribute a function type attribute to the innermost 00514 /// function chunk or type. Returns true if the attribute was 00515 /// distributed, false if no location was found. 00516 static bool 00517 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 00518 AttributeList &attr, 00519 AttributeList *&attrList, 00520 QualType &declSpecType) { 00521 Declarator &declarator = state.getDeclarator(); 00522 00523 // Put it on the innermost function chunk, if there is one. 00524 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 00525 DeclaratorChunk &chunk = declarator.getTypeObject(i); 00526 if (chunk.Kind != DeclaratorChunk::Function) continue; 00527 00528 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 00529 return true; 00530 } 00531 00532 return handleFunctionTypeAttr(state, attr, declSpecType); 00533 } 00534 00535 /// A function type attribute was written in the decl spec. Try to 00536 /// apply it somewhere. 00537 static void 00538 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 00539 AttributeList &attr, 00540 QualType &declSpecType) { 00541 state.saveDeclSpecAttrs(); 00542 00543 // C++11 attributes before the decl specifiers actually appertain to 00544 // the declarators. Move them straight there. We don't support the 00545 // 'put them wherever you like' semantics we allow for GNU attributes. 00546 if (attr.isCXX11Attribute()) { 00547 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 00548 state.getDeclarator().getAttrListRef()); 00549 return; 00550 } 00551 00552 // Try to distribute to the innermost. 00553 if (distributeFunctionTypeAttrToInnermost(state, attr, 00554 state.getCurrentAttrListRef(), 00555 declSpecType)) 00556 return; 00557 00558 // If that failed, diagnose the bad attribute when the declarator is 00559 // fully built. 00560 state.addIgnoredTypeAttr(attr); 00561 } 00562 00563 /// A function type attribute was written on the declarator. Try to 00564 /// apply it somewhere. 00565 static void 00566 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 00567 AttributeList &attr, 00568 QualType &declSpecType) { 00569 Declarator &declarator = state.getDeclarator(); 00570 00571 // Try to distribute to the innermost. 00572 if (distributeFunctionTypeAttrToInnermost(state, attr, 00573 declarator.getAttrListRef(), 00574 declSpecType)) 00575 return; 00576 00577 // If that failed, diagnose the bad attribute when the declarator is 00578 // fully built. 00579 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 00580 state.addIgnoredTypeAttr(attr); 00581 } 00582 00583 /// \brief Given that there are attributes written on the declarator 00584 /// itself, try to distribute any type attributes to the appropriate 00585 /// declarator chunk. 00586 /// 00587 /// These are attributes like the following: 00588 /// int f ATTR; 00589 /// int (f ATTR)(); 00590 /// but not necessarily this: 00591 /// int f() ATTR; 00592 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 00593 QualType &declSpecType) { 00594 // Collect all the type attributes from the declarator itself. 00595 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 00596 AttributeList *attr = state.getDeclarator().getAttributes(); 00597 AttributeList *next; 00598 do { 00599 next = attr->getNext(); 00600 00601 // Do not distribute C++11 attributes. They have strict rules for what 00602 // they appertain to. 00603 if (attr->isCXX11Attribute()) 00604 continue; 00605 00606 switch (attr->getKind()) { 00607 OBJC_POINTER_TYPE_ATTRS_CASELIST: 00608 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 00609 break; 00610 00611 case AttributeList::AT_NSReturnsRetained: 00612 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 00613 break; 00614 // fallthrough 00615 00616 FUNCTION_TYPE_ATTRS_CASELIST: 00617 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 00618 break; 00619 00620 MS_TYPE_ATTRS_CASELIST: 00621 // Microsoft type attributes cannot go after the declarator-id. 00622 continue; 00623 00624 default: 00625 break; 00626 } 00627 } while ((attr = next)); 00628 } 00629 00630 /// Add a synthetic '()' to a block-literal declarator if it is 00631 /// required, given the return type. 00632 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 00633 QualType declSpecType) { 00634 Declarator &declarator = state.getDeclarator(); 00635 00636 // First, check whether the declarator would produce a function, 00637 // i.e. whether the innermost semantic chunk is a function. 00638 if (declarator.isFunctionDeclarator()) { 00639 // If so, make that declarator a prototyped declarator. 00640 declarator.getFunctionTypeInfo().hasPrototype = true; 00641 return; 00642 } 00643 00644 // If there are any type objects, the type as written won't name a 00645 // function, regardless of the decl spec type. This is because a 00646 // block signature declarator is always an abstract-declarator, and 00647 // abstract-declarators can't just be parentheses chunks. Therefore 00648 // we need to build a function chunk unless there are no type 00649 // objects and the decl spec type is a function. 00650 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 00651 return; 00652 00653 // Note that there *are* cases with invalid declarators where 00654 // declarators consist solely of parentheses. In general, these 00655 // occur only in failed efforts to make function declarators, so 00656 // faking up the function chunk is still the right thing to do. 00657 00658 // Otherwise, we need to fake up a function declarator. 00659 SourceLocation loc = declarator.getLocStart(); 00660 00661 // ...and *prepend* it to the declarator. 00662 SourceLocation NoLoc; 00663 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 00664 /*HasProto=*/true, 00665 /*IsAmbiguous=*/false, 00666 /*LParenLoc=*/NoLoc, 00667 /*ArgInfo=*/nullptr, 00668 /*NumArgs=*/0, 00669 /*EllipsisLoc=*/NoLoc, 00670 /*RParenLoc=*/NoLoc, 00671 /*TypeQuals=*/0, 00672 /*RefQualifierIsLvalueRef=*/true, 00673 /*RefQualifierLoc=*/NoLoc, 00674 /*ConstQualifierLoc=*/NoLoc, 00675 /*VolatileQualifierLoc=*/NoLoc, 00676 /*RestrictQualifierLoc=*/NoLoc, 00677 /*MutableLoc=*/NoLoc, EST_None, 00678 /*ESpecLoc=*/NoLoc, 00679 /*Exceptions=*/nullptr, 00680 /*ExceptionRanges=*/nullptr, 00681 /*NumExceptions=*/0, 00682 /*NoexceptExpr=*/nullptr, 00683 /*ExceptionSpecTokens=*/nullptr, 00684 loc, loc, declarator)); 00685 00686 // For consistency, make sure the state still has us as processing 00687 // the decl spec. 00688 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 00689 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 00690 } 00691 00692 /// \brief Convert the specified declspec to the appropriate type 00693 /// object. 00694 /// \param state Specifies the declarator containing the declaration specifier 00695 /// to be converted, along with other associated processing state. 00696 /// \returns The type described by the declaration specifiers. This function 00697 /// never returns null. 00698 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 00699 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 00700 // checking. 00701 00702 Sema &S = state.getSema(); 00703 Declarator &declarator = state.getDeclarator(); 00704 const DeclSpec &DS = declarator.getDeclSpec(); 00705 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 00706 if (DeclLoc.isInvalid()) 00707 DeclLoc = DS.getLocStart(); 00708 00709 ASTContext &Context = S.Context; 00710 00711 QualType Result; 00712 switch (DS.getTypeSpecType()) { 00713 case DeclSpec::TST_void: 00714 Result = Context.VoidTy; 00715 break; 00716 case DeclSpec::TST_char: 00717 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 00718 Result = Context.CharTy; 00719 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 00720 Result = Context.SignedCharTy; 00721 else { 00722 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 00723 "Unknown TSS value"); 00724 Result = Context.UnsignedCharTy; 00725 } 00726 break; 00727 case DeclSpec::TST_wchar: 00728 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 00729 Result = Context.WCharTy; 00730 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 00731 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 00732 << DS.getSpecifierName(DS.getTypeSpecType(), 00733 Context.getPrintingPolicy()); 00734 Result = Context.getSignedWCharType(); 00735 } else { 00736 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 00737 "Unknown TSS value"); 00738 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 00739 << DS.getSpecifierName(DS.getTypeSpecType(), 00740 Context.getPrintingPolicy()); 00741 Result = Context.getUnsignedWCharType(); 00742 } 00743 break; 00744 case DeclSpec::TST_char16: 00745 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 00746 "Unknown TSS value"); 00747 Result = Context.Char16Ty; 00748 break; 00749 case DeclSpec::TST_char32: 00750 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 00751 "Unknown TSS value"); 00752 Result = Context.Char32Ty; 00753 break; 00754 case DeclSpec::TST_unspecified: 00755 // "<proto1,proto2>" is an objc qualified ID with a missing id. 00756 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 00757 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 00758 (ObjCProtocolDecl*const*)PQ, 00759 DS.getNumProtocolQualifiers()); 00760 Result = Context.getObjCObjectPointerType(Result); 00761 break; 00762 } 00763 00764 // If this is a missing declspec in a block literal return context, then it 00765 // is inferred from the return statements inside the block. 00766 // The declspec is always missing in a lambda expr context; it is either 00767 // specified with a trailing return type or inferred. 00768 if (S.getLangOpts().CPlusPlus14 && 00769 declarator.getContext() == Declarator::LambdaExprContext) { 00770 // In C++1y, a lambda's implicit return type is 'auto'. 00771 Result = Context.getAutoDeductType(); 00772 break; 00773 } else if (declarator.getContext() == Declarator::LambdaExprContext || 00774 isOmittedBlockReturnType(declarator)) { 00775 Result = Context.DependentTy; 00776 break; 00777 } 00778 00779 // Unspecified typespec defaults to int in C90. However, the C90 grammar 00780 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 00781 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 00782 // Note that the one exception to this is function definitions, which are 00783 // allowed to be completely missing a declspec. This is handled in the 00784 // parser already though by it pretending to have seen an 'int' in this 00785 // case. 00786 if (S.getLangOpts().ImplicitInt) { 00787 // In C89 mode, we only warn if there is a completely missing declspec 00788 // when one is not allowed. 00789 if (DS.isEmpty()) { 00790 S.Diag(DeclLoc, diag::ext_missing_declspec) 00791 << DS.getSourceRange() 00792 << FixItHint::CreateInsertion(DS.getLocStart(), "int"); 00793 } 00794 } else if (!DS.hasTypeSpecifier()) { 00795 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 00796 // "At least one type specifier shall be given in the declaration 00797 // specifiers in each declaration, and in the specifier-qualifier list in 00798 // each struct declaration and type name." 00799 if (S.getLangOpts().CPlusPlus) { 00800 S.Diag(DeclLoc, diag::err_missing_type_specifier) 00801 << DS.getSourceRange(); 00802 00803 // When this occurs in C++ code, often something is very broken with the 00804 // value being declared, poison it as invalid so we don't get chains of 00805 // errors. 00806 declarator.setInvalidType(true); 00807 } else { 00808 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 00809 << DS.getSourceRange(); 00810 } 00811 } 00812 00813 // FALL THROUGH. 00814 case DeclSpec::TST_int: { 00815 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 00816 switch (DS.getTypeSpecWidth()) { 00817 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 00818 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 00819 case DeclSpec::TSW_long: Result = Context.LongTy; break; 00820 case DeclSpec::TSW_longlong: 00821 Result = Context.LongLongTy; 00822 00823 // 'long long' is a C99 or C++11 feature. 00824 if (!S.getLangOpts().C99) { 00825 if (S.getLangOpts().CPlusPlus) 00826 S.Diag(DS.getTypeSpecWidthLoc(), 00827 S.getLangOpts().CPlusPlus11 ? 00828 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 00829 else 00830 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 00831 } 00832 break; 00833 } 00834 } else { 00835 switch (DS.getTypeSpecWidth()) { 00836 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 00837 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 00838 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 00839 case DeclSpec::TSW_longlong: 00840 Result = Context.UnsignedLongLongTy; 00841 00842 // 'long long' is a C99 or C++11 feature. 00843 if (!S.getLangOpts().C99) { 00844 if (S.getLangOpts().CPlusPlus) 00845 S.Diag(DS.getTypeSpecWidthLoc(), 00846 S.getLangOpts().CPlusPlus11 ? 00847 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 00848 else 00849 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 00850 } 00851 break; 00852 } 00853 } 00854 break; 00855 } 00856 case DeclSpec::TST_int128: 00857 if (!S.Context.getTargetInfo().hasInt128Type()) 00858 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported); 00859 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 00860 Result = Context.UnsignedInt128Ty; 00861 else 00862 Result = Context.Int128Ty; 00863 break; 00864 case DeclSpec::TST_half: Result = Context.HalfTy; break; 00865 case DeclSpec::TST_float: Result = Context.FloatTy; break; 00866 case DeclSpec::TST_double: 00867 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 00868 Result = Context.LongDoubleTy; 00869 else 00870 Result = Context.DoubleTy; 00871 00872 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 00873 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 00874 declarator.setInvalidType(true); 00875 } 00876 break; 00877 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 00878 case DeclSpec::TST_decimal32: // _Decimal32 00879 case DeclSpec::TST_decimal64: // _Decimal64 00880 case DeclSpec::TST_decimal128: // _Decimal128 00881 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 00882 Result = Context.IntTy; 00883 declarator.setInvalidType(true); 00884 break; 00885 case DeclSpec::TST_class: 00886 case DeclSpec::TST_enum: 00887 case DeclSpec::TST_union: 00888 case DeclSpec::TST_struct: 00889 case DeclSpec::TST_interface: { 00890 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 00891 if (!D) { 00892 // This can happen in C++ with ambiguous lookups. 00893 Result = Context.IntTy; 00894 declarator.setInvalidType(true); 00895 break; 00896 } 00897 00898 // If the type is deprecated or unavailable, diagnose it. 00899 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 00900 00901 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 00902 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 00903 00904 // TypeQuals handled by caller. 00905 Result = Context.getTypeDeclType(D); 00906 00907 // In both C and C++, make an ElaboratedType. 00908 ElaboratedTypeKeyword Keyword 00909 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 00910 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 00911 break; 00912 } 00913 case DeclSpec::TST_typename: { 00914 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 00915 DS.getTypeSpecSign() == 0 && 00916 "Can't handle qualifiers on typedef names yet!"); 00917 Result = S.GetTypeFromParser(DS.getRepAsType()); 00918 if (Result.isNull()) 00919 declarator.setInvalidType(true); 00920 else if (DeclSpec::ProtocolQualifierListTy PQ 00921 = DS.getProtocolQualifiers()) { 00922 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 00923 // Silently drop any existing protocol qualifiers. 00924 // TODO: determine whether that's the right thing to do. 00925 if (ObjT->getNumProtocols()) 00926 Result = ObjT->getBaseType(); 00927 00928 if (DS.getNumProtocolQualifiers()) 00929 Result = Context.getObjCObjectType(Result, 00930 (ObjCProtocolDecl*const*) PQ, 00931 DS.getNumProtocolQualifiers()); 00932 } else if (Result->isObjCIdType()) { 00933 // id<protocol-list> 00934 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 00935 (ObjCProtocolDecl*const*) PQ, 00936 DS.getNumProtocolQualifiers()); 00937 Result = Context.getObjCObjectPointerType(Result); 00938 } else if (Result->isObjCClassType()) { 00939 // Class<protocol-list> 00940 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 00941 (ObjCProtocolDecl*const*) PQ, 00942 DS.getNumProtocolQualifiers()); 00943 Result = Context.getObjCObjectPointerType(Result); 00944 } else { 00945 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 00946 << DS.getSourceRange(); 00947 declarator.setInvalidType(true); 00948 } 00949 } 00950 00951 // TypeQuals handled by caller. 00952 break; 00953 } 00954 case DeclSpec::TST_typeofType: 00955 // FIXME: Preserve type source info. 00956 Result = S.GetTypeFromParser(DS.getRepAsType()); 00957 assert(!Result.isNull() && "Didn't get a type for typeof?"); 00958 if (!Result->isDependentType()) 00959 if (const TagType *TT = Result->getAs<TagType>()) 00960 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 00961 // TypeQuals handled by caller. 00962 Result = Context.getTypeOfType(Result); 00963 break; 00964 case DeclSpec::TST_typeofExpr: { 00965 Expr *E = DS.getRepAsExpr(); 00966 assert(E && "Didn't get an expression for typeof?"); 00967 // TypeQuals handled by caller. 00968 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 00969 if (Result.isNull()) { 00970 Result = Context.IntTy; 00971 declarator.setInvalidType(true); 00972 } 00973 break; 00974 } 00975 case DeclSpec::TST_decltype: { 00976 Expr *E = DS.getRepAsExpr(); 00977 assert(E && "Didn't get an expression for decltype?"); 00978 // TypeQuals handled by caller. 00979 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 00980 if (Result.isNull()) { 00981 Result = Context.IntTy; 00982 declarator.setInvalidType(true); 00983 } 00984 break; 00985 } 00986 case DeclSpec::TST_underlyingType: 00987 Result = S.GetTypeFromParser(DS.getRepAsType()); 00988 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 00989 Result = S.BuildUnaryTransformType(Result, 00990 UnaryTransformType::EnumUnderlyingType, 00991 DS.getTypeSpecTypeLoc()); 00992 if (Result.isNull()) { 00993 Result = Context.IntTy; 00994 declarator.setInvalidType(true); 00995 } 00996 break; 00997 00998 case DeclSpec::TST_auto: 00999 // TypeQuals handled by caller. 01000 // If auto is mentioned in a lambda parameter context, convert it to a 01001 // template parameter type immediately, with the appropriate depth and 01002 // index, and update sema's state (LambdaScopeInfo) for the current lambda 01003 // being analyzed (which tracks the invented type template parameter). 01004 if (declarator.getContext() == Declarator::LambdaExprParameterContext) { 01005 sema::LambdaScopeInfo *LSI = S.getCurLambda(); 01006 assert(LSI && "No LambdaScopeInfo on the stack!"); 01007 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; 01008 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size(); 01009 const bool IsParameterPack = declarator.hasEllipsis(); 01010 01011 // Create a name for the invented template parameter type. 01012 std::string InventedTemplateParamName = "$auto-"; 01013 llvm::raw_string_ostream ss(InventedTemplateParamName); 01014 ss << TemplateParameterDepth; 01015 ss << "-" << AutoParameterPosition; 01016 ss.flush(); 01017 01018 IdentifierInfo& TemplateParamII = Context.Idents.get( 01019 InventedTemplateParamName.c_str()); 01020 // Turns out we must create the TemplateTypeParmDecl here to 01021 // retrieve the corresponding template parameter type. 01022 TemplateTypeParmDecl *CorrespondingTemplateParam = 01023 TemplateTypeParmDecl::Create(Context, 01024 // Temporarily add to the TranslationUnit DeclContext. When the 01025 // associated TemplateParameterList is attached to a template 01026 // declaration (such as FunctionTemplateDecl), the DeclContext 01027 // for each template parameter gets updated appropriately via 01028 // a call to AdoptTemplateParameterList. 01029 Context.getTranslationUnitDecl(), 01030 /*KeyLoc*/ SourceLocation(), 01031 /*NameLoc*/ declarator.getLocStart(), 01032 TemplateParameterDepth, 01033 AutoParameterPosition, // our template param index 01034 /* Identifier*/ &TemplateParamII, false, IsParameterPack); 01035 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); 01036 // Replace the 'auto' in the function parameter with this invented 01037 // template type parameter. 01038 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0); 01039 } else { 01040 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false); 01041 } 01042 break; 01043 01044 case DeclSpec::TST_decltype_auto: 01045 Result = Context.getAutoType(QualType(), 01046 /*decltype(auto)*/true, 01047 /*IsDependent*/ false); 01048 break; 01049 01050 case DeclSpec::TST_unknown_anytype: 01051 Result = Context.UnknownAnyTy; 01052 break; 01053 01054 case DeclSpec::TST_atomic: 01055 Result = S.GetTypeFromParser(DS.getRepAsType()); 01056 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 01057 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 01058 if (Result.isNull()) { 01059 Result = Context.IntTy; 01060 declarator.setInvalidType(true); 01061 } 01062 break; 01063 01064 case DeclSpec::TST_error: 01065 Result = Context.IntTy; 01066 declarator.setInvalidType(true); 01067 break; 01068 } 01069 01070 // Handle complex types. 01071 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 01072 if (S.getLangOpts().Freestanding) 01073 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 01074 Result = Context.getComplexType(Result); 01075 } else if (DS.isTypeAltiVecVector()) { 01076 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 01077 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 01078 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 01079 if (DS.isTypeAltiVecPixel()) 01080 VecKind = VectorType::AltiVecPixel; 01081 else if (DS.isTypeAltiVecBool()) 01082 VecKind = VectorType::AltiVecBool; 01083 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 01084 } 01085 01086 // FIXME: Imaginary. 01087 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 01088 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 01089 01090 // Before we process any type attributes, synthesize a block literal 01091 // function declarator if necessary. 01092 if (declarator.getContext() == Declarator::BlockLiteralContext) 01093 maybeSynthesizeBlockSignature(state, Result); 01094 01095 // Apply any type attributes from the decl spec. This may cause the 01096 // list of type attributes to be temporarily saved while the type 01097 // attributes are pushed around. 01098 if (AttributeList *attrs = DS.getAttributes().getList()) 01099 processTypeAttrs(state, Result, TAL_DeclSpec, attrs); 01100 01101 // Apply const/volatile/restrict qualifiers to T. 01102 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 01103 01104 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 01105 // of a function type includes any type qualifiers, the behavior is 01106 // undefined." 01107 if (Result->isFunctionType() && TypeQuals) { 01108 if (TypeQuals & DeclSpec::TQ_const) 01109 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers) 01110 << Result << DS.getSourceRange(); 01111 else if (TypeQuals & DeclSpec::TQ_volatile) 01112 S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers) 01113 << Result << DS.getSourceRange(); 01114 else { 01115 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) && 01116 "Has CVRA quals but not C, V, R, or A?"); 01117 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a 01118 // function type later, in BuildQualifiedType. 01119 } 01120 } 01121 01122 // C++11 [dcl.ref]p1: 01123 // Cv-qualified references are ill-formed except when the 01124 // cv-qualifiers are introduced through the use of a typedef-name 01125 // or decltype-specifier, in which case the cv-qualifiers are ignored. 01126 // 01127 // There don't appear to be any other contexts in which a cv-qualified 01128 // reference type could be formed, so the 'ill-formed' clause here appears 01129 // to never happen. 01130 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 01131 TypeQuals && Result->isReferenceType()) { 01132 // If this occurs outside a template instantiation, warn the user about 01133 // it; they probably didn't mean to specify a redundant qualifier. 01134 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; 01135 QualLoc Quals[] = { 01136 QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), 01137 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), 01138 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc()) 01139 }; 01140 for (unsigned I = 0, N = llvm::array_lengthof(Quals); I != N; ++I) { 01141 if (S.ActiveTemplateInstantiations.empty()) { 01142 if (TypeQuals & Quals[I].first) 01143 S.Diag(Quals[I].second, diag::warn_typecheck_reference_qualifiers) 01144 << DeclSpec::getSpecifierName(Quals[I].first) << Result 01145 << FixItHint::CreateRemoval(Quals[I].second); 01146 } 01147 TypeQuals &= ~Quals[I].first; 01148 } 01149 } 01150 01151 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 01152 // than once in the same specifier-list or qualifier-list, either directly 01153 // or via one or more typedefs." 01154 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 01155 && TypeQuals & Result.getCVRQualifiers()) { 01156 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 01157 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 01158 << "const"; 01159 } 01160 01161 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 01162 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 01163 << "volatile"; 01164 } 01165 01166 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to 01167 // produce a warning in this case. 01168 } 01169 01170 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); 01171 01172 // If adding qualifiers fails, just use the unqualified type. 01173 if (Qualified.isNull()) 01174 declarator.setInvalidType(true); 01175 else 01176 Result = Qualified; 01177 } 01178 01179 return Result; 01180 } 01181 01182 static std::string getPrintableNameForEntity(DeclarationName Entity) { 01183 if (Entity) 01184 return Entity.getAsString(); 01185 01186 return "type name"; 01187 } 01188 01189 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 01190 Qualifiers Qs, const DeclSpec *DS) { 01191 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 01192 // object or incomplete types shall not be restrict-qualified." 01193 if (Qs.hasRestrict()) { 01194 unsigned DiagID = 0; 01195 QualType ProblemTy; 01196 01197 if (T->isAnyPointerType() || T->isReferenceType() || 01198 T->isMemberPointerType()) { 01199 QualType EltTy; 01200 if (T->isObjCObjectPointerType()) 01201 EltTy = T; 01202 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) 01203 EltTy = PTy->getPointeeType(); 01204 else 01205 EltTy = T->getPointeeType(); 01206 01207 // If we have a pointer or reference, the pointee must have an object 01208 // incomplete type. 01209 if (!EltTy->isIncompleteOrObjectType()) { 01210 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 01211 ProblemTy = EltTy; 01212 } 01213 } else if (!T->isDependentType()) { 01214 DiagID = diag::err_typecheck_invalid_restrict_not_pointer; 01215 ProblemTy = T; 01216 } 01217 01218 if (DiagID) { 01219 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; 01220 Qs.removeRestrict(); 01221 } 01222 } 01223 01224 return Context.getQualifiedType(T, Qs); 01225 } 01226 01227 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 01228 unsigned CVRA, const DeclSpec *DS) { 01229 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic. 01230 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic; 01231 01232 // C11 6.7.3/5: 01233 // If the same qualifier appears more than once in the same 01234 // specifier-qualifier-list, either directly or via one or more typedefs, 01235 // the behavior is the same as if it appeared only once. 01236 // 01237 // It's not specified what happens when the _Atomic qualifier is applied to 01238 // a type specified with the _Atomic specifier, but we assume that this 01239 // should be treated as if the _Atomic qualifier appeared multiple times. 01240 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) { 01241 // C11 6.7.3/5: 01242 // If other qualifiers appear along with the _Atomic qualifier in a 01243 // specifier-qualifier-list, the resulting type is the so-qualified 01244 // atomic type. 01245 // 01246 // Don't need to worry about array types here, since _Atomic can't be 01247 // applied to such types. 01248 SplitQualType Split = T.getSplitUnqualifiedType(); 01249 T = BuildAtomicType(QualType(Split.Ty, 0), 01250 DS ? DS->getAtomicSpecLoc() : Loc); 01251 if (T.isNull()) 01252 return T; 01253 Split.Quals.addCVRQualifiers(CVR); 01254 return BuildQualifiedType(T, Loc, Split.Quals); 01255 } 01256 01257 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS); 01258 } 01259 01260 /// \brief Build a paren type including \p T. 01261 QualType Sema::BuildParenType(QualType T) { 01262 return Context.getParenType(T); 01263 } 01264 01265 /// Given that we're building a pointer or reference to the given 01266 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 01267 SourceLocation loc, 01268 bool isReference) { 01269 // Bail out if retention is unrequired or already specified. 01270 if (!type->isObjCLifetimeType() || 01271 type.getObjCLifetime() != Qualifiers::OCL_None) 01272 return type; 01273 01274 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 01275 01276 // If the object type is const-qualified, we can safely use 01277 // __unsafe_unretained. This is safe (because there are no read 01278 // barriers), and it'll be safe to coerce anything but __weak* to 01279 // the resulting type. 01280 if (type.isConstQualified()) { 01281 implicitLifetime = Qualifiers::OCL_ExplicitNone; 01282 01283 // Otherwise, check whether the static type does not require 01284 // retaining. This currently only triggers for Class (possibly 01285 // protocol-qualifed, and arrays thereof). 01286 } else if (type->isObjCARCImplicitlyUnretainedType()) { 01287 implicitLifetime = Qualifiers::OCL_ExplicitNone; 01288 01289 // If we are in an unevaluated context, like sizeof, skip adding a 01290 // qualification. 01291 } else if (S.isUnevaluatedContext()) { 01292 return type; 01293 01294 // If that failed, give an error and recover using __strong. __strong 01295 // is the option most likely to prevent spurious second-order diagnostics, 01296 // like when binding a reference to a field. 01297 } else { 01298 // These types can show up in private ivars in system headers, so 01299 // we need this to not be an error in those cases. Instead we 01300 // want to delay. 01301 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 01302 S.DelayedDiagnostics.add( 01303 sema::DelayedDiagnostic::makeForbiddenType(loc, 01304 diag::err_arc_indirect_no_ownership, type, isReference)); 01305 } else { 01306 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 01307 } 01308 implicitLifetime = Qualifiers::OCL_Strong; 01309 } 01310 assert(implicitLifetime && "didn't infer any lifetime!"); 01311 01312 Qualifiers qs; 01313 qs.addObjCLifetime(implicitLifetime); 01314 return S.Context.getQualifiedType(type, qs); 01315 } 01316 01317 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 01318 std::string Quals = 01319 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 01320 01321 switch (FnTy->getRefQualifier()) { 01322 case RQ_None: 01323 break; 01324 01325 case RQ_LValue: 01326 if (!Quals.empty()) 01327 Quals += ' '; 01328 Quals += '&'; 01329 break; 01330 01331 case RQ_RValue: 01332 if (!Quals.empty()) 01333 Quals += ' '; 01334 Quals += "&&"; 01335 break; 01336 } 01337 01338 return Quals; 01339 } 01340 01341 namespace { 01342 /// Kinds of declarator that cannot contain a qualified function type. 01343 /// 01344 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: 01345 /// a function type with a cv-qualifier or a ref-qualifier can only appear 01346 /// at the topmost level of a type. 01347 /// 01348 /// Parens and member pointers are permitted. We don't diagnose array and 01349 /// function declarators, because they don't allow function types at all. 01350 /// 01351 /// The values of this enum are used in diagnostics. 01352 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; 01353 } 01354 01355 /// Check whether the type T is a qualified function type, and if it is, 01356 /// diagnose that it cannot be contained within the given kind of declarator. 01357 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, 01358 QualifiedFunctionKind QFK) { 01359 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 01360 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); 01361 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None)) 01362 return false; 01363 01364 S.Diag(Loc, diag::err_compound_qualified_function_type) 01365 << QFK << isa<FunctionType>(T.IgnoreParens()) << T 01366 << getFunctionQualifiersAsString(FPT); 01367 return true; 01368 } 01369 01370 /// \brief Build a pointer type. 01371 /// 01372 /// \param T The type to which we'll be building a pointer. 01373 /// 01374 /// \param Loc The location of the entity whose type involves this 01375 /// pointer type or, if there is no such entity, the location of the 01376 /// type that will have pointer type. 01377 /// 01378 /// \param Entity The name of the entity that involves the pointer 01379 /// type, if known. 01380 /// 01381 /// \returns A suitable pointer type, if there are no 01382 /// errors. Otherwise, returns a NULL type. 01383 QualType Sema::BuildPointerType(QualType T, 01384 SourceLocation Loc, DeclarationName Entity) { 01385 if (T->isReferenceType()) { 01386 // C++ 8.3.2p4: There shall be no ... pointers to references ... 01387 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 01388 << getPrintableNameForEntity(Entity) << T; 01389 return QualType(); 01390 } 01391 01392 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) 01393 return QualType(); 01394 01395 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 01396 01397 // In ARC, it is forbidden to build pointers to unqualified pointers. 01398 if (getLangOpts().ObjCAutoRefCount) 01399 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 01400 01401 // Build the pointer type. 01402 return Context.getPointerType(T); 01403 } 01404 01405 /// \brief Build a reference type. 01406 /// 01407 /// \param T The type to which we'll be building a reference. 01408 /// 01409 /// \param Loc The location of the entity whose type involves this 01410 /// reference type or, if there is no such entity, the location of the 01411 /// type that will have reference type. 01412 /// 01413 /// \param Entity The name of the entity that involves the reference 01414 /// type, if known. 01415 /// 01416 /// \returns A suitable reference type, if there are no 01417 /// errors. Otherwise, returns a NULL type. 01418 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 01419 SourceLocation Loc, 01420 DeclarationName Entity) { 01421 assert(Context.getCanonicalType(T) != Context.OverloadTy && 01422 "Unresolved overloaded function type"); 01423 01424 // C++0x [dcl.ref]p6: 01425 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 01426 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 01427 // type T, an attempt to create the type "lvalue reference to cv TR" creates 01428 // the type "lvalue reference to T", while an attempt to create the type 01429 // "rvalue reference to cv TR" creates the type TR. 01430 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 01431 01432 // C++ [dcl.ref]p4: There shall be no references to references. 01433 // 01434 // According to C++ DR 106, references to references are only 01435 // diagnosed when they are written directly (e.g., "int & &"), 01436 // but not when they happen via a typedef: 01437 // 01438 // typedef int& intref; 01439 // typedef intref& intref2; 01440 // 01441 // Parser::ParseDeclaratorInternal diagnoses the case where 01442 // references are written directly; here, we handle the 01443 // collapsing of references-to-references as described in C++0x. 01444 // DR 106 and 540 introduce reference-collapsing into C++98/03. 01445 01446 // C++ [dcl.ref]p1: 01447 // A declarator that specifies the type "reference to cv void" 01448 // is ill-formed. 01449 if (T->isVoidType()) { 01450 Diag(Loc, diag::err_reference_to_void); 01451 return QualType(); 01452 } 01453 01454 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) 01455 return QualType(); 01456 01457 // In ARC, it is forbidden to build references to unqualified pointers. 01458 if (getLangOpts().ObjCAutoRefCount) 01459 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 01460 01461 // Handle restrict on references. 01462 if (LValueRef) 01463 return Context.getLValueReferenceType(T, SpelledAsLValue); 01464 return Context.getRValueReferenceType(T); 01465 } 01466 01467 /// Check whether the specified array size makes the array type a VLA. If so, 01468 /// return true, if not, return the size of the array in SizeVal. 01469 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 01470 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 01471 // (like gnu99, but not c99) accept any evaluatable value as an extension. 01472 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 01473 public: 01474 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 01475 01476 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 01477 } 01478 01479 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { 01480 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 01481 } 01482 } Diagnoser; 01483 01484 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 01485 S.LangOpts.GNUMode).isInvalid(); 01486 } 01487 01488 01489 /// \brief Build an array type. 01490 /// 01491 /// \param T The type of each element in the array. 01492 /// 01493 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 01494 /// 01495 /// \param ArraySize Expression describing the size of the array. 01496 /// 01497 /// \param Brackets The range from the opening '[' to the closing ']'. 01498 /// 01499 /// \param Entity The name of the entity that involves the array 01500 /// type, if known. 01501 /// 01502 /// \returns A suitable array type, if there are no errors. Otherwise, 01503 /// returns a NULL type. 01504 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 01505 Expr *ArraySize, unsigned Quals, 01506 SourceRange Brackets, DeclarationName Entity) { 01507 01508 SourceLocation Loc = Brackets.getBegin(); 01509 if (getLangOpts().CPlusPlus) { 01510 // C++ [dcl.array]p1: 01511 // T is called the array element type; this type shall not be a reference 01512 // type, the (possibly cv-qualified) type void, a function type or an 01513 // abstract class type. 01514 // 01515 // C++ [dcl.array]p3: 01516 // When several "array of" specifications are adjacent, [...] only the 01517 // first of the constant expressions that specify the bounds of the arrays 01518 // may be omitted. 01519 // 01520 // Note: function types are handled in the common path with C. 01521 if (T->isReferenceType()) { 01522 Diag(Loc, diag::err_illegal_decl_array_of_references) 01523 << getPrintableNameForEntity(Entity) << T; 01524 return QualType(); 01525 } 01526 01527 if (T->isVoidType() || T->isIncompleteArrayType()) { 01528 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 01529 return QualType(); 01530 } 01531 01532 if (RequireNonAbstractType(Brackets.getBegin(), T, 01533 diag::err_array_of_abstract_type)) 01534 return QualType(); 01535 01536 // Mentioning a member pointer type for an array type causes us to lock in 01537 // an inheritance model, even if it's inside an unused typedef. 01538 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 01539 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) 01540 if (!MPTy->getClass()->isDependentType()) 01541 RequireCompleteType(Loc, T, 0); 01542 01543 } else { 01544 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 01545 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 01546 if (RequireCompleteType(Loc, T, 01547 diag::err_illegal_decl_array_incomplete_type)) 01548 return QualType(); 01549 } 01550 01551 if (T->isFunctionType()) { 01552 Diag(Loc, diag::err_illegal_decl_array_of_functions) 01553 << getPrintableNameForEntity(Entity) << T; 01554 return QualType(); 01555 } 01556 01557 if (const RecordType *EltTy = T->getAs<RecordType>()) { 01558 // If the element type is a struct or union that contains a variadic 01559 // array, accept it as a GNU extension: C99 6.7.2.1p2. 01560 if (EltTy->getDecl()->hasFlexibleArrayMember()) 01561 Diag(Loc, diag::ext_flexible_array_in_array) << T; 01562 } else if (T->isObjCObjectType()) { 01563 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 01564 return QualType(); 01565 } 01566 01567 // Do placeholder conversions on the array size expression. 01568 if (ArraySize && ArraySize->hasPlaceholderType()) { 01569 ExprResult Result = CheckPlaceholderExpr(ArraySize); 01570 if (Result.isInvalid()) return QualType(); 01571 ArraySize = Result.get(); 01572 } 01573 01574 // Do lvalue-to-rvalue conversions on the array size expression. 01575 if (ArraySize && !ArraySize->isRValue()) { 01576 ExprResult Result = DefaultLvalueConversion(ArraySize); 01577 if (Result.isInvalid()) 01578 return QualType(); 01579 01580 ArraySize = Result.get(); 01581 } 01582 01583 // C99 6.7.5.2p1: The size expression shall have integer type. 01584 // C++11 allows contextual conversions to such types. 01585 if (!getLangOpts().CPlusPlus11 && 01586 ArraySize && !ArraySize->isTypeDependent() && 01587 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 01588 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 01589 << ArraySize->getType() << ArraySize->getSourceRange(); 01590 return QualType(); 01591 } 01592 01593 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 01594 if (!ArraySize) { 01595 if (ASM == ArrayType::Star) 01596 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); 01597 else 01598 T = Context.getIncompleteArrayType(T, ASM, Quals); 01599 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 01600 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 01601 } else if ((!T->isDependentType() && !T->isIncompleteType() && 01602 !T->isConstantSizeType()) || 01603 isArraySizeVLA(*this, ArraySize, ConstVal)) { 01604 // Even in C++11, don't allow contextual conversions in the array bound 01605 // of a VLA. 01606 if (getLangOpts().CPlusPlus11 && 01607 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 01608 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 01609 << ArraySize->getType() << ArraySize->getSourceRange(); 01610 return QualType(); 01611 } 01612 01613 // C99: an array with an element type that has a non-constant-size is a VLA. 01614 // C99: an array with a non-ICE size is a VLA. We accept any expression 01615 // that we can fold to a non-zero positive value as an extension. 01616 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 01617 } else { 01618 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 01619 // have a value greater than zero. 01620 if (ConstVal.isSigned() && ConstVal.isNegative()) { 01621 if (Entity) 01622 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 01623 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 01624 else 01625 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 01626 << ArraySize->getSourceRange(); 01627 return QualType(); 01628 } 01629 if (ConstVal == 0) { 01630 // GCC accepts zero sized static arrays. We allow them when 01631 // we're not in a SFINAE context. 01632 Diag(ArraySize->getLocStart(), 01633 isSFINAEContext()? diag::err_typecheck_zero_array_size 01634 : diag::ext_typecheck_zero_array_size) 01635 << ArraySize->getSourceRange(); 01636 01637 if (ASM == ArrayType::Static) { 01638 Diag(ArraySize->getLocStart(), 01639 diag::warn_typecheck_zero_static_array_size) 01640 << ArraySize->getSourceRange(); 01641 ASM = ArrayType::Normal; 01642 } 01643 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 01644 !T->isIncompleteType() && !T->isUndeducedType()) { 01645 // Is the array too large? 01646 unsigned ActiveSizeBits 01647 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 01648 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 01649 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 01650 << ConstVal.toString(10) 01651 << ArraySize->getSourceRange(); 01652 return QualType(); 01653 } 01654 } 01655 01656 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 01657 } 01658 01659 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 01660 if (getLangOpts().OpenCL && T->isVariableArrayType()) { 01661 Diag(Loc, diag::err_opencl_vla); 01662 return QualType(); 01663 } 01664 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 01665 if (!getLangOpts().C99) { 01666 if (T->isVariableArrayType()) { 01667 // Prohibit the use of non-POD types in VLAs. 01668 QualType BaseT = Context.getBaseElementType(T); 01669 if (!T->isDependentType() && 01670 !RequireCompleteType(Loc, BaseT, 0) && 01671 !BaseT.isPODType(Context) && 01672 !BaseT->isObjCLifetimeType()) { 01673 Diag(Loc, diag::err_vla_non_pod) 01674 << BaseT; 01675 return QualType(); 01676 } 01677 // Prohibit the use of VLAs during template argument deduction. 01678 else if (isSFINAEContext()) { 01679 Diag(Loc, diag::err_vla_in_sfinae); 01680 return QualType(); 01681 } 01682 // Just extwarn about VLAs. 01683 else 01684 Diag(Loc, diag::ext_vla); 01685 } else if (ASM != ArrayType::Normal || Quals != 0) 01686 Diag(Loc, 01687 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 01688 : diag::ext_c99_array_usage) << ASM; 01689 } 01690 01691 if (T->isVariableArrayType()) { 01692 // Warn about VLAs for -Wvla. 01693 Diag(Loc, diag::warn_vla_used); 01694 } 01695 01696 return T; 01697 } 01698 01699 /// \brief Build an ext-vector type. 01700 /// 01701 /// Run the required checks for the extended vector type. 01702 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 01703 SourceLocation AttrLoc) { 01704 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 01705 // in conjunction with complex types (pointers, arrays, functions, etc.). 01706 if (!T->isDependentType() && 01707 !T->isIntegerType() && !T->isRealFloatingType()) { 01708 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 01709 return QualType(); 01710 } 01711 01712 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 01713 llvm::APSInt vecSize(32); 01714 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 01715 Diag(AttrLoc, diag::err_attribute_argument_type) 01716 << "ext_vector_type" << AANT_ArgumentIntegerConstant 01717 << ArraySize->getSourceRange(); 01718 return QualType(); 01719 } 01720 01721 // unlike gcc's vector_size attribute, the size is specified as the 01722 // number of elements, not the number of bytes. 01723 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 01724 01725 if (vectorSize == 0) { 01726 Diag(AttrLoc, diag::err_attribute_zero_size) 01727 << ArraySize->getSourceRange(); 01728 return QualType(); 01729 } 01730 01731 if (VectorType::isVectorSizeTooLarge(vectorSize)) { 01732 Diag(AttrLoc, diag::err_attribute_size_too_large) 01733 << ArraySize->getSourceRange(); 01734 return QualType(); 01735 } 01736 01737 return Context.getExtVectorType(T, vectorSize); 01738 } 01739 01740 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 01741 } 01742 01743 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 01744 if (T->isArrayType() || T->isFunctionType()) { 01745 Diag(Loc, diag::err_func_returning_array_function) 01746 << T->isFunctionType() << T; 01747 return true; 01748 } 01749 01750 // Functions cannot return half FP. 01751 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 01752 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 01753 FixItHint::CreateInsertion(Loc, "*"); 01754 return true; 01755 } 01756 01757 // Methods cannot return interface types. All ObjC objects are 01758 // passed by reference. 01759 if (T->isObjCObjectType()) { 01760 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T; 01761 return 0; 01762 } 01763 01764 return false; 01765 } 01766 01767 QualType Sema::BuildFunctionType(QualType T, 01768 MutableArrayRef<QualType> ParamTypes, 01769 SourceLocation Loc, DeclarationName Entity, 01770 const FunctionProtoType::ExtProtoInfo &EPI) { 01771 bool Invalid = false; 01772 01773 Invalid |= CheckFunctionReturnType(T, Loc); 01774 01775 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 01776 // FIXME: Loc is too inprecise here, should use proper locations for args. 01777 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 01778 if (ParamType->isVoidType()) { 01779 Diag(Loc, diag::err_param_with_void_type); 01780 Invalid = true; 01781 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 01782 // Disallow half FP arguments. 01783 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 01784 FixItHint::CreateInsertion(Loc, "*"); 01785 Invalid = true; 01786 } 01787 01788 ParamTypes[Idx] = ParamType; 01789 } 01790 01791 if (Invalid) 01792 return QualType(); 01793 01794 return Context.getFunctionType(T, ParamTypes, EPI); 01795 } 01796 01797 /// \brief Build a member pointer type \c T Class::*. 01798 /// 01799 /// \param T the type to which the member pointer refers. 01800 /// \param Class the class type into which the member pointer points. 01801 /// \param Loc the location where this type begins 01802 /// \param Entity the name of the entity that will have this member pointer type 01803 /// 01804 /// \returns a member pointer type, if successful, or a NULL type if there was 01805 /// an error. 01806 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 01807 SourceLocation Loc, 01808 DeclarationName Entity) { 01809 // Verify that we're not building a pointer to pointer to function with 01810 // exception specification. 01811 if (CheckDistantExceptionSpec(T)) { 01812 Diag(Loc, diag::err_distant_exception_spec); 01813 01814 // FIXME: If we're doing this as part of template instantiation, 01815 // we should return immediately. 01816 01817 // Build the type anyway, but use the canonical type so that the 01818 // exception specifiers are stripped off. 01819 T = Context.getCanonicalType(T); 01820 } 01821 01822 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 01823 // with reference type, or "cv void." 01824 if (T->isReferenceType()) { 01825 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 01826 << getPrintableNameForEntity(Entity) << T; 01827 return QualType(); 01828 } 01829 01830 if (T->isVoidType()) { 01831 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 01832 << getPrintableNameForEntity(Entity); 01833 return QualType(); 01834 } 01835 01836 if (!Class->isDependentType() && !Class->isRecordType()) { 01837 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 01838 return QualType(); 01839 } 01840 01841 // Adjust the default free function calling convention to the default method 01842 // calling convention. 01843 if (T->isFunctionType()) 01844 adjustMemberFunctionCC(T, /*IsStatic=*/false); 01845 01846 return Context.getMemberPointerType(T, Class.getTypePtr()); 01847 } 01848 01849 /// \brief Build a block pointer type. 01850 /// 01851 /// \param T The type to which we'll be building a block pointer. 01852 /// 01853 /// \param Loc The source location, used for diagnostics. 01854 /// 01855 /// \param Entity The name of the entity that involves the block pointer 01856 /// type, if known. 01857 /// 01858 /// \returns A suitable block pointer type, if there are no 01859 /// errors. Otherwise, returns a NULL type. 01860 QualType Sema::BuildBlockPointerType(QualType T, 01861 SourceLocation Loc, 01862 DeclarationName Entity) { 01863 if (!T->isFunctionType()) { 01864 Diag(Loc, diag::err_nonfunction_block_type); 01865 return QualType(); 01866 } 01867 01868 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) 01869 return QualType(); 01870 01871 return Context.getBlockPointerType(T); 01872 } 01873 01874 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 01875 QualType QT = Ty.get(); 01876 if (QT.isNull()) { 01877 if (TInfo) *TInfo = nullptr; 01878 return QualType(); 01879 } 01880 01881 TypeSourceInfo *DI = nullptr; 01882 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 01883 QT = LIT->getType(); 01884 DI = LIT->getTypeSourceInfo(); 01885 } 01886 01887 if (TInfo) *TInfo = DI; 01888 return QT; 01889 } 01890 01891 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 01892 Qualifiers::ObjCLifetime ownership, 01893 unsigned chunkIndex); 01894 01895 /// Given that this is the declaration of a parameter under ARC, 01896 /// attempt to infer attributes and such for pointer-to-whatever 01897 /// types. 01898 static void inferARCWriteback(TypeProcessingState &state, 01899 QualType &declSpecType) { 01900 Sema &S = state.getSema(); 01901 Declarator &declarator = state.getDeclarator(); 01902 01903 // TODO: should we care about decl qualifiers? 01904 01905 // Check whether the declarator has the expected form. We walk 01906 // from the inside out in order to make the block logic work. 01907 unsigned outermostPointerIndex = 0; 01908 bool isBlockPointer = false; 01909 unsigned numPointers = 0; 01910 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 01911 unsigned chunkIndex = i; 01912 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 01913 switch (chunk.Kind) { 01914 case DeclaratorChunk::Paren: 01915 // Ignore parens. 01916 break; 01917 01918 case DeclaratorChunk::Reference: 01919 case DeclaratorChunk::Pointer: 01920 // Count the number of pointers. Treat references 01921 // interchangeably as pointers; if they're mis-ordered, normal 01922 // type building will discover that. 01923 outermostPointerIndex = chunkIndex; 01924 numPointers++; 01925 break; 01926 01927 case DeclaratorChunk::BlockPointer: 01928 // If we have a pointer to block pointer, that's an acceptable 01929 // indirect reference; anything else is not an application of 01930 // the rules. 01931 if (numPointers != 1) return; 01932 numPointers++; 01933 outermostPointerIndex = chunkIndex; 01934 isBlockPointer = true; 01935 01936 // We don't care about pointer structure in return values here. 01937 goto done; 01938 01939 case DeclaratorChunk::Array: // suppress if written (id[])? 01940 case DeclaratorChunk::Function: 01941 case DeclaratorChunk::MemberPointer: 01942 return; 01943 } 01944 } 01945 done: 01946 01947 // If we have *one* pointer, then we want to throw the qualifier on 01948 // the declaration-specifiers, which means that it needs to be a 01949 // retainable object type. 01950 if (numPointers == 1) { 01951 // If it's not a retainable object type, the rule doesn't apply. 01952 if (!declSpecType->isObjCRetainableType()) return; 01953 01954 // If it already has lifetime, don't do anything. 01955 if (declSpecType.getObjCLifetime()) return; 01956 01957 // Otherwise, modify the type in-place. 01958 Qualifiers qs; 01959 01960 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 01961 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 01962 else 01963 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 01964 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 01965 01966 // If we have *two* pointers, then we want to throw the qualifier on 01967 // the outermost pointer. 01968 } else if (numPointers == 2) { 01969 // If we don't have a block pointer, we need to check whether the 01970 // declaration-specifiers gave us something that will turn into a 01971 // retainable object pointer after we slap the first pointer on it. 01972 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 01973 return; 01974 01975 // Look for an explicit lifetime attribute there. 01976 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 01977 if (chunk.Kind != DeclaratorChunk::Pointer && 01978 chunk.Kind != DeclaratorChunk::BlockPointer) 01979 return; 01980 for (const AttributeList *attr = chunk.getAttrs(); attr; 01981 attr = attr->getNext()) 01982 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 01983 return; 01984 01985 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 01986 outermostPointerIndex); 01987 01988 // Any other number of pointers/references does not trigger the rule. 01989 } else return; 01990 01991 // TODO: mark whether we did this inference? 01992 } 01993 01994 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 01995 SourceLocation FallbackLoc, 01996 SourceLocation ConstQualLoc, 01997 SourceLocation VolatileQualLoc, 01998 SourceLocation RestrictQualLoc, 01999 SourceLocation AtomicQualLoc) { 02000 if (!Quals) 02001 return; 02002 02003 struct Qual { 02004 unsigned Mask; 02005 const char *Name; 02006 SourceLocation Loc; 02007 } const QualKinds[4] = { 02008 { DeclSpec::TQ_const, "const", ConstQualLoc }, 02009 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc }, 02010 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc }, 02011 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc } 02012 }; 02013 02014 SmallString<32> QualStr; 02015 unsigned NumQuals = 0; 02016 SourceLocation Loc; 02017 FixItHint FixIts[4]; 02018 02019 // Build a string naming the redundant qualifiers. 02020 for (unsigned I = 0; I != 4; ++I) { 02021 if (Quals & QualKinds[I].Mask) { 02022 if (!QualStr.empty()) QualStr += ' '; 02023 QualStr += QualKinds[I].Name; 02024 02025 // If we have a location for the qualifier, offer a fixit. 02026 SourceLocation QualLoc = QualKinds[I].Loc; 02027 if (!QualLoc.isInvalid()) { 02028 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 02029 if (Loc.isInvalid() || 02030 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) 02031 Loc = QualLoc; 02032 } 02033 02034 ++NumQuals; 02035 } 02036 } 02037 02038 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) 02039 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 02040 } 02041 02042 // Diagnose pointless type qualifiers on the return type of a function. 02043 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, 02044 Declarator &D, 02045 unsigned FunctionChunkIndex) { 02046 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 02047 // FIXME: TypeSourceInfo doesn't preserve location information for 02048 // qualifiers. 02049 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 02050 RetTy.getLocalCVRQualifiers(), 02051 D.getIdentifierLoc()); 02052 return; 02053 } 02054 02055 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 02056 End = D.getNumTypeObjects(); 02057 OuterChunkIndex != End; ++OuterChunkIndex) { 02058 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 02059 switch (OuterChunk.Kind) { 02060 case DeclaratorChunk::Paren: 02061 continue; 02062 02063 case DeclaratorChunk::Pointer: { 02064 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 02065 S.diagnoseIgnoredQualifiers( 02066 diag::warn_qual_return_type, 02067 PTI.TypeQuals, 02068 SourceLocation(), 02069 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 02070 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 02071 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 02072 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 02073 return; 02074 } 02075 02076 case DeclaratorChunk::Function: 02077 case DeclaratorChunk::BlockPointer: 02078 case DeclaratorChunk::Reference: 02079 case DeclaratorChunk::Array: 02080 case DeclaratorChunk::MemberPointer: 02081 // FIXME: We can't currently provide an accurate source location and a 02082 // fix-it hint for these. 02083 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 02084 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 02085 RetTy.getCVRQualifiers() | AtomicQual, 02086 D.getIdentifierLoc()); 02087 return; 02088 } 02089 02090 llvm_unreachable("unknown declarator chunk kind"); 02091 } 02092 02093 // If the qualifiers come from a conversion function type, don't diagnose 02094 // them -- they're not necessarily redundant, since such a conversion 02095 // operator can be explicitly called as "x.operator const int()". 02096 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 02097 return; 02098 02099 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 02100 // which are present there. 02101 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 02102 D.getDeclSpec().getTypeQualifiers(), 02103 D.getIdentifierLoc(), 02104 D.getDeclSpec().getConstSpecLoc(), 02105 D.getDeclSpec().getVolatileSpecLoc(), 02106 D.getDeclSpec().getRestrictSpecLoc(), 02107 D.getDeclSpec().getAtomicSpecLoc()); 02108 } 02109 02110 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 02111 TypeSourceInfo *&ReturnTypeInfo) { 02112 Sema &SemaRef = state.getSema(); 02113 Declarator &D = state.getDeclarator(); 02114 QualType T; 02115 ReturnTypeInfo = nullptr; 02116 02117 // The TagDecl owned by the DeclSpec. 02118 TagDecl *OwnedTagDecl = nullptr; 02119 02120 bool ContainsPlaceholderType = false; 02121 02122 switch (D.getName().getKind()) { 02123 case UnqualifiedId::IK_ImplicitSelfParam: 02124 case UnqualifiedId::IK_OperatorFunctionId: 02125 case UnqualifiedId::IK_Identifier: 02126 case UnqualifiedId::IK_LiteralOperatorId: 02127 case UnqualifiedId::IK_TemplateId: 02128 T = ConvertDeclSpecToType(state); 02129 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType(); 02130 02131 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 02132 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 02133 // Owned declaration is embedded in declarator. 02134 OwnedTagDecl->setEmbeddedInDeclarator(true); 02135 } 02136 break; 02137 02138 case UnqualifiedId::IK_ConstructorName: 02139 case UnqualifiedId::IK_ConstructorTemplateId: 02140 case UnqualifiedId::IK_DestructorName: 02141 // Constructors and destructors don't have return types. Use 02142 // "void" instead. 02143 T = SemaRef.Context.VoidTy; 02144 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList()) 02145 processTypeAttrs(state, T, TAL_DeclSpec, attrs); 02146 break; 02147 02148 case UnqualifiedId::IK_ConversionFunctionId: 02149 // The result type of a conversion function is the type that it 02150 // converts to. 02151 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 02152 &ReturnTypeInfo); 02153 ContainsPlaceholderType = T->getContainedAutoType(); 02154 break; 02155 } 02156 02157 if (D.getAttributes()) 02158 distributeTypeAttrsFromDeclarator(state, T); 02159 02160 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 02161 // In C++11, a function declarator using 'auto' must have a trailing return 02162 // type (this is checked later) and we can skip this. In other languages 02163 // using auto, we need to check regardless. 02164 // C++14 In generic lambdas allow 'auto' in their parameters. 02165 if (ContainsPlaceholderType && 02166 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) { 02167 int Error = -1; 02168 02169 switch (D.getContext()) { 02170 case Declarator::KNRTypeListContext: 02171 llvm_unreachable("K&R type lists aren't allowed in C++"); 02172 case Declarator::LambdaExprContext: 02173 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 02174 case Declarator::ObjCParameterContext: 02175 case Declarator::ObjCResultContext: 02176 case Declarator::PrototypeContext: 02177 Error = 0; 02178 break; 02179 case Declarator::LambdaExprParameterContext: 02180 if (!(SemaRef.getLangOpts().CPlusPlus14 02181 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto)) 02182 Error = 14; 02183 break; 02184 case Declarator::MemberContext: 02185 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 02186 break; 02187 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 02188 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 02189 case TTK_Struct: Error = 1; /* Struct member */ break; 02190 case TTK_Union: Error = 2; /* Union member */ break; 02191 case TTK_Class: Error = 3; /* Class member */ break; 02192 case TTK_Interface: Error = 4; /* Interface member */ break; 02193 } 02194 break; 02195 case Declarator::CXXCatchContext: 02196 case Declarator::ObjCCatchContext: 02197 Error = 5; // Exception declaration 02198 break; 02199 case Declarator::TemplateParamContext: 02200 Error = 6; // Template parameter 02201 break; 02202 case Declarator::BlockLiteralContext: 02203 Error = 7; // Block literal 02204 break; 02205 case Declarator::TemplateTypeArgContext: 02206 Error = 8; // Template type argument 02207 break; 02208 case Declarator::AliasDeclContext: 02209 case Declarator::AliasTemplateContext: 02210 Error = 10; // Type alias 02211 break; 02212 case Declarator::TrailingReturnContext: 02213 if (!SemaRef.getLangOpts().CPlusPlus14) 02214 Error = 11; // Function return type 02215 break; 02216 case Declarator::ConversionIdContext: 02217 if (!SemaRef.getLangOpts().CPlusPlus14) 02218 Error = 12; // conversion-type-id 02219 break; 02220 case Declarator::TypeNameContext: 02221 Error = 13; // Generic 02222 break; 02223 case Declarator::FileContext: 02224 case Declarator::BlockContext: 02225 case Declarator::ForContext: 02226 case Declarator::ConditionContext: 02227 case Declarator::CXXNewContext: 02228 break; 02229 } 02230 02231 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 02232 Error = 9; 02233 02234 // In Objective-C it is an error to use 'auto' on a function declarator. 02235 if (D.isFunctionDeclarator()) 02236 Error = 11; 02237 02238 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 02239 // contains a trailing return type. That is only legal at the outermost 02240 // level. Check all declarator chunks (outermost first) anyway, to give 02241 // better diagnostics. 02242 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) { 02243 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 02244 unsigned chunkIndex = e - i - 1; 02245 state.setCurrentChunkIndex(chunkIndex); 02246 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 02247 if (DeclType.Kind == DeclaratorChunk::Function) { 02248 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 02249 if (FTI.hasTrailingReturnType()) { 02250 Error = -1; 02251 break; 02252 } 02253 } 02254 } 02255 } 02256 02257 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 02258 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 02259 AutoRange = D.getName().getSourceRange(); 02260 02261 if (Error != -1) { 02262 const bool IsDeclTypeAuto = 02263 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto; 02264 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 02265 << IsDeclTypeAuto << Error << AutoRange; 02266 T = SemaRef.Context.IntTy; 02267 D.setInvalidType(true); 02268 } else 02269 SemaRef.Diag(AutoRange.getBegin(), 02270 diag::warn_cxx98_compat_auto_type_specifier) 02271 << AutoRange; 02272 } 02273 02274 if (SemaRef.getLangOpts().CPlusPlus && 02275 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 02276 // Check the contexts where C++ forbids the declaration of a new class 02277 // or enumeration in a type-specifier-seq. 02278 switch (D.getContext()) { 02279 case Declarator::TrailingReturnContext: 02280 // Class and enumeration definitions are syntactically not allowed in 02281 // trailing return types. 02282 llvm_unreachable("parser should not have allowed this"); 02283 break; 02284 case Declarator::FileContext: 02285 case Declarator::MemberContext: 02286 case Declarator::BlockContext: 02287 case Declarator::ForContext: 02288 case Declarator::BlockLiteralContext: 02289 case Declarator::LambdaExprContext: 02290 // C++11 [dcl.type]p3: 02291 // A type-specifier-seq shall not define a class or enumeration unless 02292 // it appears in the type-id of an alias-declaration (7.1.3) that is not 02293 // the declaration of a template-declaration. 02294 case Declarator::AliasDeclContext: 02295 break; 02296 case Declarator::AliasTemplateContext: 02297 SemaRef.Diag(OwnedTagDecl->getLocation(), 02298 diag::err_type_defined_in_alias_template) 02299 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 02300 D.setInvalidType(true); 02301 break; 02302 case Declarator::TypeNameContext: 02303 case Declarator::ConversionIdContext: 02304 case Declarator::TemplateParamContext: 02305 case Declarator::CXXNewContext: 02306 case Declarator::CXXCatchContext: 02307 case Declarator::ObjCCatchContext: 02308 case Declarator::TemplateTypeArgContext: 02309 SemaRef.Diag(OwnedTagDecl->getLocation(), 02310 diag::err_type_defined_in_type_specifier) 02311 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 02312 D.setInvalidType(true); 02313 break; 02314 case Declarator::PrototypeContext: 02315 case Declarator::LambdaExprParameterContext: 02316 case Declarator::ObjCParameterContext: 02317 case Declarator::ObjCResultContext: 02318 case Declarator::KNRTypeListContext: 02319 // C++ [dcl.fct]p6: 02320 // Types shall not be defined in return or parameter types. 02321 SemaRef.Diag(OwnedTagDecl->getLocation(), 02322 diag::err_type_defined_in_param_type) 02323 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 02324 D.setInvalidType(true); 02325 break; 02326 case Declarator::ConditionContext: 02327 // C++ 6.4p2: 02328 // The type-specifier-seq shall not contain typedef and shall not declare 02329 // a new class or enumeration. 02330 SemaRef.Diag(OwnedTagDecl->getLocation(), 02331 diag::err_type_defined_in_condition); 02332 D.setInvalidType(true); 02333 break; 02334 } 02335 } 02336 02337 return T; 02338 } 02339 02340 /// Produce an appropriate diagnostic for an ambiguity between a function 02341 /// declarator and a C++ direct-initializer. 02342 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 02343 DeclaratorChunk &DeclType, QualType RT) { 02344 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 02345 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 02346 02347 // If the return type is void there is no ambiguity. 02348 if (RT->isVoidType()) 02349 return; 02350 02351 // An initializer for a non-class type can have at most one argument. 02352 if (!RT->isRecordType() && FTI.NumParams > 1) 02353 return; 02354 02355 // An initializer for a reference must have exactly one argument. 02356 if (RT->isReferenceType() && FTI.NumParams != 1) 02357 return; 02358 02359 // Only warn if this declarator is declaring a function at block scope, and 02360 // doesn't have a storage class (such as 'extern') specified. 02361 if (!D.isFunctionDeclarator() || 02362 D.getFunctionDefinitionKind() != FDK_Declaration || 02363 !S.CurContext->isFunctionOrMethod() || 02364 D.getDeclSpec().getStorageClassSpec() 02365 != DeclSpec::SCS_unspecified) 02366 return; 02367 02368 // Inside a condition, a direct initializer is not permitted. We allow one to 02369 // be parsed in order to give better diagnostics in condition parsing. 02370 if (D.getContext() == Declarator::ConditionContext) 02371 return; 02372 02373 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 02374 02375 S.Diag(DeclType.Loc, 02376 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 02377 : diag::warn_empty_parens_are_function_decl) 02378 << ParenRange; 02379 02380 // If the declaration looks like: 02381 // T var1, 02382 // f(); 02383 // and name lookup finds a function named 'f', then the ',' was 02384 // probably intended to be a ';'. 02385 if (!D.isFirstDeclarator() && D.getIdentifier()) { 02386 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 02387 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 02388 if (Comma.getFileID() != Name.getFileID() || 02389 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 02390 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 02391 Sema::LookupOrdinaryName); 02392 if (S.LookupName(Result, S.getCurScope())) 02393 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 02394 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 02395 << D.getIdentifier(); 02396 } 02397 } 02398 02399 if (FTI.NumParams > 0) { 02400 // For a declaration with parameters, eg. "T var(T());", suggest adding 02401 // parens around the first parameter to turn the declaration into a 02402 // variable declaration. 02403 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 02404 SourceLocation B = Range.getBegin(); 02405 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 02406 // FIXME: Maybe we should suggest adding braces instead of parens 02407 // in C++11 for classes that don't have an initializer_list constructor. 02408 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 02409 << FixItHint::CreateInsertion(B, "(") 02410 << FixItHint::CreateInsertion(E, ")"); 02411 } else { 02412 // For a declaration without parameters, eg. "T var();", suggest replacing 02413 // the parens with an initializer to turn the declaration into a variable 02414 // declaration. 02415 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 02416 02417 // Empty parens mean value-initialization, and no parens mean 02418 // default initialization. These are equivalent if the default 02419 // constructor is user-provided or if zero-initialization is a 02420 // no-op. 02421 if (RD && RD->hasDefinition() && 02422 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 02423 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 02424 << FixItHint::CreateRemoval(ParenRange); 02425 else { 02426 std::string Init = 02427 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 02428 if (Init.empty() && S.LangOpts.CPlusPlus11) 02429 Init = "{}"; 02430 if (!Init.empty()) 02431 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 02432 << FixItHint::CreateReplacement(ParenRange, Init); 02433 } 02434 } 02435 } 02436 02437 /// Helper for figuring out the default CC for a function declarator type. If 02438 /// this is the outermost chunk, then we can determine the CC from the 02439 /// declarator context. If not, then this could be either a member function 02440 /// type or normal function type. 02441 static CallingConv 02442 getCCForDeclaratorChunk(Sema &S, Declarator &D, 02443 const DeclaratorChunk::FunctionTypeInfo &FTI, 02444 unsigned ChunkIndex) { 02445 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 02446 02447 bool IsCXXInstanceMethod = false; 02448 02449 if (S.getLangOpts().CPlusPlus) { 02450 // Look inwards through parentheses to see if this chunk will form a 02451 // member pointer type or if we're the declarator. Any type attributes 02452 // between here and there will override the CC we choose here. 02453 unsigned I = ChunkIndex; 02454 bool FoundNonParen = false; 02455 while (I && !FoundNonParen) { 02456 --I; 02457 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 02458 FoundNonParen = true; 02459 } 02460 02461 if (FoundNonParen) { 02462 // If we're not the declarator, we're a regular function type unless we're 02463 // in a member pointer. 02464 IsCXXInstanceMethod = 02465 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 02466 } else { 02467 // We're the innermost decl chunk, so must be a function declarator. 02468 assert(D.isFunctionDeclarator()); 02469 02470 // If we're inside a record, we're declaring a method, but it could be 02471 // explicitly or implicitly static. 02472 IsCXXInstanceMethod = 02473 D.isFirstDeclarationOfMember() && 02474 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 02475 !D.isStaticMember(); 02476 } 02477 } 02478 02479 return S.Context.getDefaultCallingConvention(FTI.isVariadic, 02480 IsCXXInstanceMethod); 02481 } 02482 02483 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 02484 QualType declSpecType, 02485 TypeSourceInfo *TInfo) { 02486 02487 QualType T = declSpecType; 02488 Declarator &D = state.getDeclarator(); 02489 Sema &S = state.getSema(); 02490 ASTContext &Context = S.Context; 02491 const LangOptions &LangOpts = S.getLangOpts(); 02492 02493 // The name we're declaring, if any. 02494 DeclarationName Name; 02495 if (D.getIdentifier()) 02496 Name = D.getIdentifier(); 02497 02498 // Does this declaration declare a typedef-name? 02499 bool IsTypedefName = 02500 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 02501 D.getContext() == Declarator::AliasDeclContext || 02502 D.getContext() == Declarator::AliasTemplateContext; 02503 02504 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 02505 bool IsQualifiedFunction = T->isFunctionProtoType() && 02506 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 02507 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 02508 02509 // If T is 'decltype(auto)', the only declarators we can have are parens 02510 // and at most one function declarator if this is a function declaration. 02511 if (const AutoType *AT = T->getAs<AutoType>()) { 02512 if (AT->isDecltypeAuto()) { 02513 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 02514 unsigned Index = E - I - 1; 02515 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 02516 unsigned DiagId = diag::err_decltype_auto_compound_type; 02517 unsigned DiagKind = 0; 02518 switch (DeclChunk.Kind) { 02519 case DeclaratorChunk::Paren: 02520 continue; 02521 case DeclaratorChunk::Function: { 02522 unsigned FnIndex; 02523 if (D.isFunctionDeclarationContext() && 02524 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 02525 continue; 02526 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 02527 break; 02528 } 02529 case DeclaratorChunk::Pointer: 02530 case DeclaratorChunk::BlockPointer: 02531 case DeclaratorChunk::MemberPointer: 02532 DiagKind = 0; 02533 break; 02534 case DeclaratorChunk::Reference: 02535 DiagKind = 1; 02536 break; 02537 case DeclaratorChunk::Array: 02538 DiagKind = 2; 02539 break; 02540 } 02541 02542 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 02543 D.setInvalidType(true); 02544 break; 02545 } 02546 } 02547 } 02548 02549 // Walk the DeclTypeInfo, building the recursive type as we go. 02550 // DeclTypeInfos are ordered from the identifier out, which is 02551 // opposite of what we want :). 02552 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 02553 unsigned chunkIndex = e - i - 1; 02554 state.setCurrentChunkIndex(chunkIndex); 02555 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 02556 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 02557 switch (DeclType.Kind) { 02558 case DeclaratorChunk::Paren: 02559 T = S.BuildParenType(T); 02560 break; 02561 case DeclaratorChunk::BlockPointer: 02562 // If blocks are disabled, emit an error. 02563 if (!LangOpts.Blocks) 02564 S.Diag(DeclType.Loc, diag::err_blocks_disable); 02565 02566 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 02567 if (DeclType.Cls.TypeQuals) 02568 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 02569 break; 02570 case DeclaratorChunk::Pointer: 02571 // Verify that we're not building a pointer to pointer to function with 02572 // exception specification. 02573 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 02574 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 02575 D.setInvalidType(true); 02576 // Build the type anyway. 02577 } 02578 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 02579 T = Context.getObjCObjectPointerType(T); 02580 if (DeclType.Ptr.TypeQuals) 02581 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 02582 break; 02583 } 02584 T = S.BuildPointerType(T, DeclType.Loc, Name); 02585 if (DeclType.Ptr.TypeQuals) 02586 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 02587 02588 break; 02589 case DeclaratorChunk::Reference: { 02590 // Verify that we're not building a reference to pointer to function with 02591 // exception specification. 02592 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 02593 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 02594 D.setInvalidType(true); 02595 // Build the type anyway. 02596 } 02597 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 02598 02599 if (DeclType.Ref.HasRestrict) 02600 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 02601 break; 02602 } 02603 case DeclaratorChunk::Array: { 02604 // Verify that we're not building an array of pointers to function with 02605 // exception specification. 02606 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 02607 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 02608 D.setInvalidType(true); 02609 // Build the type anyway. 02610 } 02611 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 02612 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 02613 ArrayType::ArraySizeModifier ASM; 02614 if (ATI.isStar) 02615 ASM = ArrayType::Star; 02616 else if (ATI.hasStatic) 02617 ASM = ArrayType::Static; 02618 else 02619 ASM = ArrayType::Normal; 02620 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 02621 // FIXME: This check isn't quite right: it allows star in prototypes 02622 // for function definitions, and disallows some edge cases detailed 02623 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 02624 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 02625 ASM = ArrayType::Normal; 02626 D.setInvalidType(true); 02627 } 02628 02629 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 02630 // shall appear only in a declaration of a function parameter with an 02631 // array type, ... 02632 if (ASM == ArrayType::Static || ATI.TypeQuals) { 02633 if (!(D.isPrototypeContext() || 02634 D.getContext() == Declarator::KNRTypeListContext)) { 02635 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 02636 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 02637 // Remove the 'static' and the type qualifiers. 02638 if (ASM == ArrayType::Static) 02639 ASM = ArrayType::Normal; 02640 ATI.TypeQuals = 0; 02641 D.setInvalidType(true); 02642 } 02643 02644 // C99 6.7.5.2p1: ... and then only in the outermost array type 02645 // derivation. 02646 unsigned x = chunkIndex; 02647 while (x != 0) { 02648 // Walk outwards along the declarator chunks. 02649 x--; 02650 const DeclaratorChunk &DC = D.getTypeObject(x); 02651 switch (DC.Kind) { 02652 case DeclaratorChunk::Paren: 02653 continue; 02654 case DeclaratorChunk::Array: 02655 case DeclaratorChunk::Pointer: 02656 case DeclaratorChunk::Reference: 02657 case DeclaratorChunk::MemberPointer: 02658 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 02659 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 02660 if (ASM == ArrayType::Static) 02661 ASM = ArrayType::Normal; 02662 ATI.TypeQuals = 0; 02663 D.setInvalidType(true); 02664 break; 02665 case DeclaratorChunk::Function: 02666 case DeclaratorChunk::BlockPointer: 02667 // These are invalid anyway, so just ignore. 02668 break; 02669 } 02670 } 02671 } 02672 const AutoType *AT = T->getContainedAutoType(); 02673 // Allow arrays of auto if we are a generic lambda parameter. 02674 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 02675 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) { 02676 // We've already diagnosed this for decltype(auto). 02677 if (!AT->isDecltypeAuto()) 02678 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 02679 << getPrintableNameForEntity(Name) << T; 02680 T = QualType(); 02681 break; 02682 } 02683 02684 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 02685 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 02686 break; 02687 } 02688 case DeclaratorChunk::Function: { 02689 // If the function declarator has a prototype (i.e. it is not () and 02690 // does not have a K&R-style identifier list), then the arguments are part 02691 // of the type, otherwise the argument list is (). 02692 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 02693 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 02694 02695 // Check for auto functions and trailing return type and adjust the 02696 // return type accordingly. 02697 if (!D.isInvalidType()) { 02698 // trailing-return-type is only required if we're declaring a function, 02699 // and not, for instance, a pointer to a function. 02700 if (D.getDeclSpec().containsPlaceholderType() && 02701 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 02702 !S.getLangOpts().CPlusPlus14) { 02703 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 02704 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 02705 ? diag::err_auto_missing_trailing_return 02706 : diag::err_deduced_return_type); 02707 T = Context.IntTy; 02708 D.setInvalidType(true); 02709 } else if (FTI.hasTrailingReturnType()) { 02710 // T must be exactly 'auto' at this point. See CWG issue 681. 02711 if (isa<ParenType>(T)) { 02712 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 02713 diag::err_trailing_return_in_parens) 02714 << T << D.getDeclSpec().getSourceRange(); 02715 D.setInvalidType(true); 02716 } else if (D.getContext() != Declarator::LambdaExprContext && 02717 (T.hasQualifiers() || !isa<AutoType>(T) || 02718 cast<AutoType>(T)->isDecltypeAuto())) { 02719 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 02720 diag::err_trailing_return_without_auto) 02721 << T << D.getDeclSpec().getSourceRange(); 02722 D.setInvalidType(true); 02723 } 02724 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 02725 if (T.isNull()) { 02726 // An error occurred parsing the trailing return type. 02727 T = Context.IntTy; 02728 D.setInvalidType(true); 02729 } 02730 } 02731 } 02732 02733 // C99 6.7.5.3p1: The return type may not be a function or array type. 02734 // For conversion functions, we'll diagnose this particular error later. 02735 if ((T->isArrayType() || T->isFunctionType()) && 02736 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 02737 unsigned diagID = diag::err_func_returning_array_function; 02738 // Last processing chunk in block context means this function chunk 02739 // represents the block. 02740 if (chunkIndex == 0 && 02741 D.getContext() == Declarator::BlockLiteralContext) 02742 diagID = diag::err_block_returning_array_function; 02743 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 02744 T = Context.IntTy; 02745 D.setInvalidType(true); 02746 } 02747 02748 // Do not allow returning half FP value. 02749 // FIXME: This really should be in BuildFunctionType. 02750 if (T->isHalfType()) { 02751 if (S.getLangOpts().OpenCL) { 02752 if (!S.getOpenCLOptions().cl_khr_fp16) { 02753 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 02754 D.setInvalidType(true); 02755 } 02756 } else if (!S.getLangOpts().HalfArgsAndReturns) { 02757 S.Diag(D.getIdentifierLoc(), 02758 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 02759 D.setInvalidType(true); 02760 } 02761 } 02762 02763 // Methods cannot return interface types. All ObjC objects are 02764 // passed by reference. 02765 if (T->isObjCObjectType()) { 02766 SourceLocation DiagLoc, FixitLoc; 02767 if (TInfo) { 02768 DiagLoc = TInfo->getTypeLoc().getLocStart(); 02769 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 02770 } else { 02771 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 02772 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 02773 } 02774 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 02775 << 0 << T 02776 << FixItHint::CreateInsertion(FixitLoc, "*"); 02777 02778 T = Context.getObjCObjectPointerType(T); 02779 if (TInfo) { 02780 TypeLocBuilder TLB; 02781 TLB.pushFullCopy(TInfo->getTypeLoc()); 02782 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 02783 TLoc.setStarLoc(FixitLoc); 02784 TInfo = TLB.getTypeSourceInfo(Context, T); 02785 } 02786 02787 D.setInvalidType(true); 02788 } 02789 02790 // cv-qualifiers on return types are pointless except when the type is a 02791 // class type in C++. 02792 if ((T.getCVRQualifiers() || T->isAtomicType()) && 02793 !(S.getLangOpts().CPlusPlus && 02794 (T->isDependentType() || T->isRecordType()))) 02795 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 02796 02797 // Objective-C ARC ownership qualifiers are ignored on the function 02798 // return type (by type canonicalization). Complain if this attribute 02799 // was written here. 02800 if (T.getQualifiers().hasObjCLifetime()) { 02801 SourceLocation AttrLoc; 02802 if (chunkIndex + 1 < D.getNumTypeObjects()) { 02803 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 02804 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 02805 Attr; Attr = Attr->getNext()) { 02806 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 02807 AttrLoc = Attr->getLoc(); 02808 break; 02809 } 02810 } 02811 } 02812 if (AttrLoc.isInvalid()) { 02813 for (const AttributeList *Attr 02814 = D.getDeclSpec().getAttributes().getList(); 02815 Attr; Attr = Attr->getNext()) { 02816 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 02817 AttrLoc = Attr->getLoc(); 02818 break; 02819 } 02820 } 02821 } 02822 02823 if (AttrLoc.isValid()) { 02824 // The ownership attributes are almost always written via 02825 // the predefined 02826 // __strong/__weak/__autoreleasing/__unsafe_unretained. 02827 if (AttrLoc.isMacroID()) 02828 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 02829 02830 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 02831 << T.getQualifiers().getObjCLifetime(); 02832 } 02833 } 02834 02835 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 02836 // C++ [dcl.fct]p6: 02837 // Types shall not be defined in return or parameter types. 02838 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 02839 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 02840 << Context.getTypeDeclType(Tag); 02841 } 02842 02843 // Exception specs are not allowed in typedefs. Complain, but add it 02844 // anyway. 02845 if (IsTypedefName && FTI.getExceptionSpecType()) 02846 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 02847 << (D.getContext() == Declarator::AliasDeclContext || 02848 D.getContext() == Declarator::AliasTemplateContext); 02849 02850 // If we see "T var();" or "T var(T());" at block scope, it is probably 02851 // an attempt to initialize a variable, not a function declaration. 02852 if (FTI.isAmbiguous) 02853 warnAboutAmbiguousFunction(S, D, DeclType, T); 02854 02855 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 02856 02857 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) { 02858 // Simple void foo(), where the incoming T is the result type. 02859 T = Context.getFunctionNoProtoType(T, EI); 02860 } else { 02861 // We allow a zero-parameter variadic function in C if the 02862 // function is marked with the "overloadable" attribute. Scan 02863 // for this attribute now. 02864 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 02865 bool Overloadable = false; 02866 for (const AttributeList *Attrs = D.getAttributes(); 02867 Attrs; Attrs = Attrs->getNext()) { 02868 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 02869 Overloadable = true; 02870 break; 02871 } 02872 } 02873 02874 if (!Overloadable) 02875 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 02876 } 02877 02878 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 02879 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 02880 // definition. 02881 S.Diag(FTI.Params[0].IdentLoc, 02882 diag::err_ident_list_in_fn_declaration); 02883 D.setInvalidType(true); 02884 // Recover by creating a K&R-style function type. 02885 T = Context.getFunctionNoProtoType(T, EI); 02886 break; 02887 } 02888 02889 FunctionProtoType::ExtProtoInfo EPI; 02890 EPI.ExtInfo = EI; 02891 EPI.Variadic = FTI.isVariadic; 02892 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 02893 EPI.TypeQuals = FTI.TypeQuals; 02894 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 02895 : FTI.RefQualifierIsLValueRef? RQ_LValue 02896 : RQ_RValue; 02897 02898 // Otherwise, we have a function with a parameter list that is 02899 // potentially variadic. 02900 SmallVector<QualType, 16> ParamTys; 02901 ParamTys.reserve(FTI.NumParams); 02902 02903 SmallVector<bool, 16> ConsumedParameters; 02904 ConsumedParameters.reserve(FTI.NumParams); 02905 bool HasAnyConsumedParameters = false; 02906 02907 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 02908 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 02909 QualType ParamTy = Param->getType(); 02910 assert(!ParamTy.isNull() && "Couldn't parse type?"); 02911 02912 // Look for 'void'. void is allowed only as a single parameter to a 02913 // function with no other parameters (C99 6.7.5.3p10). We record 02914 // int(void) as a FunctionProtoType with an empty parameter list. 02915 if (ParamTy->isVoidType()) { 02916 // If this is something like 'float(int, void)', reject it. 'void' 02917 // is an incomplete type (C99 6.2.5p19) and function decls cannot 02918 // have parameters of incomplete type. 02919 if (FTI.NumParams != 1 || FTI.isVariadic) { 02920 S.Diag(DeclType.Loc, diag::err_void_only_param); 02921 ParamTy = Context.IntTy; 02922 Param->setType(ParamTy); 02923 } else if (FTI.Params[i].Ident) { 02924 // Reject, but continue to parse 'int(void abc)'. 02925 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 02926 ParamTy = Context.IntTy; 02927 Param->setType(ParamTy); 02928 } else { 02929 // Reject, but continue to parse 'float(const void)'. 02930 if (ParamTy.hasQualifiers()) 02931 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 02932 02933 // Do not add 'void' to the list. 02934 break; 02935 } 02936 } else if (ParamTy->isHalfType()) { 02937 // Disallow half FP parameters. 02938 // FIXME: This really should be in BuildFunctionType. 02939 if (S.getLangOpts().OpenCL) { 02940 if (!S.getOpenCLOptions().cl_khr_fp16) { 02941 S.Diag(Param->getLocation(), 02942 diag::err_opencl_half_param) << ParamTy; 02943 D.setInvalidType(); 02944 Param->setInvalidDecl(); 02945 } 02946 } else if (!S.getLangOpts().HalfArgsAndReturns) { 02947 S.Diag(Param->getLocation(), 02948 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 02949 D.setInvalidType(); 02950 } 02951 } else if (!FTI.hasPrototype) { 02952 if (ParamTy->isPromotableIntegerType()) { 02953 ParamTy = Context.getPromotedIntegerType(ParamTy); 02954 Param->setKNRPromoted(true); 02955 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 02956 if (BTy->getKind() == BuiltinType::Float) { 02957 ParamTy = Context.DoubleTy; 02958 Param->setKNRPromoted(true); 02959 } 02960 } 02961 } 02962 02963 if (LangOpts.ObjCAutoRefCount) { 02964 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 02965 ConsumedParameters.push_back(Consumed); 02966 HasAnyConsumedParameters |= Consumed; 02967 } 02968 02969 ParamTys.push_back(ParamTy); 02970 } 02971 02972 if (HasAnyConsumedParameters) 02973 EPI.ConsumedParameters = ConsumedParameters.data(); 02974 02975 SmallVector<QualType, 4> Exceptions; 02976 SmallVector<ParsedType, 2> DynamicExceptions; 02977 SmallVector<SourceRange, 2> DynamicExceptionRanges; 02978 Expr *NoexceptExpr = nullptr; 02979 02980 if (FTI.getExceptionSpecType() == EST_Dynamic) { 02981 // FIXME: It's rather inefficient to have to split into two vectors 02982 // here. 02983 unsigned N = FTI.NumExceptions; 02984 DynamicExceptions.reserve(N); 02985 DynamicExceptionRanges.reserve(N); 02986 for (unsigned I = 0; I != N; ++I) { 02987 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 02988 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 02989 } 02990 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 02991 NoexceptExpr = FTI.NoexceptExpr; 02992 } 02993 02994 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 02995 FTI.getExceptionSpecType(), 02996 DynamicExceptions, 02997 DynamicExceptionRanges, 02998 NoexceptExpr, 02999 Exceptions, 03000 EPI.ExceptionSpec); 03001 03002 T = Context.getFunctionType(T, ParamTys, EPI); 03003 } 03004 03005 break; 03006 } 03007 case DeclaratorChunk::MemberPointer: 03008 // The scope spec must refer to a class, or be dependent. 03009 CXXScopeSpec &SS = DeclType.Mem.Scope(); 03010 QualType ClsType; 03011 if (SS.isInvalid()) { 03012 // Avoid emitting extra errors if we already errored on the scope. 03013 D.setInvalidType(true); 03014 } else if (S.isDependentScopeSpecifier(SS) || 03015 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 03016 NestedNameSpecifier *NNS = SS.getScopeRep(); 03017 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 03018 switch (NNS->getKind()) { 03019 case NestedNameSpecifier::Identifier: 03020 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 03021 NNS->getAsIdentifier()); 03022 break; 03023 03024 case NestedNameSpecifier::Namespace: 03025 case NestedNameSpecifier::NamespaceAlias: 03026 case NestedNameSpecifier::Global: 03027 case NestedNameSpecifier::Super: 03028 llvm_unreachable("Nested-name-specifier must name a type"); 03029 03030 case NestedNameSpecifier::TypeSpec: 03031 case NestedNameSpecifier::TypeSpecWithTemplate: 03032 ClsType = QualType(NNS->getAsType(), 0); 03033 // Note: if the NNS has a prefix and ClsType is a nondependent 03034 // TemplateSpecializationType, then the NNS prefix is NOT included 03035 // in ClsType; hence we wrap ClsType into an ElaboratedType. 03036 // NOTE: in particular, no wrap occurs if ClsType already is an 03037 // Elaborated, DependentName, or DependentTemplateSpecialization. 03038 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 03039 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 03040 break; 03041 } 03042 } else { 03043 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 03044 diag::err_illegal_decl_mempointer_in_nonclass) 03045 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 03046 << DeclType.Mem.Scope().getRange(); 03047 D.setInvalidType(true); 03048 } 03049 03050 if (!ClsType.isNull()) 03051 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 03052 if (T.isNull()) { 03053 T = Context.IntTy; 03054 D.setInvalidType(true); 03055 } else if (DeclType.Mem.TypeQuals) { 03056 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 03057 } 03058 break; 03059 } 03060 03061 if (T.isNull()) { 03062 D.setInvalidType(true); 03063 T = Context.IntTy; 03064 } 03065 03066 // See if there are any attributes on this declarator chunk. 03067 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 03068 processTypeAttrs(state, T, TAL_DeclChunk, attrs); 03069 } 03070 03071 if (LangOpts.CPlusPlus && T->isFunctionType()) { 03072 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 03073 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 03074 03075 // C++ 8.3.5p4: 03076 // A cv-qualifier-seq shall only be part of the function type 03077 // for a nonstatic member function, the function type to which a pointer 03078 // to member refers, or the top-level function type of a function typedef 03079 // declaration. 03080 // 03081 // Core issue 547 also allows cv-qualifiers on function types that are 03082 // top-level template type arguments. 03083 bool FreeFunction; 03084 if (!D.getCXXScopeSpec().isSet()) { 03085 FreeFunction = ((D.getContext() != Declarator::MemberContext && 03086 D.getContext() != Declarator::LambdaExprContext) || 03087 D.getDeclSpec().isFriendSpecified()); 03088 } else { 03089 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 03090 FreeFunction = (DC && !DC->isRecord()); 03091 } 03092 03093 // C++11 [dcl.fct]p6 (w/DR1417): 03094 // An attempt to specify a function type with a cv-qualifier-seq or a 03095 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 03096 // - the function type for a non-static member function, 03097 // - the function type to which a pointer to member refers, 03098 // - the top-level function type of a function typedef declaration or 03099 // alias-declaration, 03100 // - the type-id in the default argument of a type-parameter, or 03101 // - the type-id of a template-argument for a type-parameter 03102 // 03103 // FIXME: Checking this here is insufficient. We accept-invalid on: 03104 // 03105 // template<typename T> struct S { void f(T); }; 03106 // S<int() const> s; 03107 // 03108 // ... for instance. 03109 if (IsQualifiedFunction && 03110 !(!FreeFunction && 03111 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 03112 !IsTypedefName && 03113 D.getContext() != Declarator::TemplateTypeArgContext) { 03114 SourceLocation Loc = D.getLocStart(); 03115 SourceRange RemovalRange; 03116 unsigned I; 03117 if (D.isFunctionDeclarator(I)) { 03118 SmallVector<SourceLocation, 4> RemovalLocs; 03119 const DeclaratorChunk &Chunk = D.getTypeObject(I); 03120 assert(Chunk.Kind == DeclaratorChunk::Function); 03121 if (Chunk.Fun.hasRefQualifier()) 03122 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 03123 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 03124 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 03125 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 03126 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 03127 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 03128 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 03129 if (!RemovalLocs.empty()) { 03130 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 03131 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 03132 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 03133 Loc = RemovalLocs.front(); 03134 } 03135 } 03136 03137 S.Diag(Loc, diag::err_invalid_qualified_function_type) 03138 << FreeFunction << D.isFunctionDeclarator() << T 03139 << getFunctionQualifiersAsString(FnTy) 03140 << FixItHint::CreateRemoval(RemovalRange); 03141 03142 // Strip the cv-qualifiers and ref-qualifiers from the type. 03143 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 03144 EPI.TypeQuals = 0; 03145 EPI.RefQualifier = RQ_None; 03146 03147 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 03148 EPI); 03149 // Rebuild any parens around the identifier in the function type. 03150 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 03151 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 03152 break; 03153 T = S.BuildParenType(T); 03154 } 03155 } 03156 } 03157 03158 // Apply any undistributed attributes from the declarator. 03159 if (!T.isNull()) 03160 if (AttributeList *attrs = D.getAttributes()) 03161 processTypeAttrs(state, T, TAL_DeclName, attrs); 03162 03163 // Diagnose any ignored type attributes. 03164 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 03165 03166 // C++0x [dcl.constexpr]p9: 03167 // A constexpr specifier used in an object declaration declares the object 03168 // as const. 03169 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 03170 T.addConst(); 03171 } 03172 03173 // If there was an ellipsis in the declarator, the declaration declares a 03174 // parameter pack whose type may be a pack expansion type. 03175 if (D.hasEllipsis() && !T.isNull()) { 03176 // C++0x [dcl.fct]p13: 03177 // A declarator-id or abstract-declarator containing an ellipsis shall 03178 // only be used in a parameter-declaration. Such a parameter-declaration 03179 // is a parameter pack (14.5.3). [...] 03180 switch (D.getContext()) { 03181 case Declarator::PrototypeContext: 03182 case Declarator::LambdaExprParameterContext: 03183 // C++0x [dcl.fct]p13: 03184 // [...] When it is part of a parameter-declaration-clause, the 03185 // parameter pack is a function parameter pack (14.5.3). The type T 03186 // of the declarator-id of the function parameter pack shall contain 03187 // a template parameter pack; each template parameter pack in T is 03188 // expanded by the function parameter pack. 03189 // 03190 // We represent function parameter packs as function parameters whose 03191 // type is a pack expansion. 03192 if (!T->containsUnexpandedParameterPack()) { 03193 S.Diag(D.getEllipsisLoc(), 03194 diag::err_function_parameter_pack_without_parameter_packs) 03195 << T << D.getSourceRange(); 03196 D.setEllipsisLoc(SourceLocation()); 03197 } else { 03198 T = Context.getPackExpansionType(T, None); 03199 } 03200 break; 03201 case Declarator::TemplateParamContext: 03202 // C++0x [temp.param]p15: 03203 // If a template-parameter is a [...] is a parameter-declaration that 03204 // declares a parameter pack (8.3.5), then the template-parameter is a 03205 // template parameter pack (14.5.3). 03206 // 03207 // Note: core issue 778 clarifies that, if there are any unexpanded 03208 // parameter packs in the type of the non-type template parameter, then 03209 // it expands those parameter packs. 03210 if (T->containsUnexpandedParameterPack()) 03211 T = Context.getPackExpansionType(T, None); 03212 else 03213 S.Diag(D.getEllipsisLoc(), 03214 LangOpts.CPlusPlus11 03215 ? diag::warn_cxx98_compat_variadic_templates 03216 : diag::ext_variadic_templates); 03217 break; 03218 03219 case Declarator::FileContext: 03220 case Declarator::KNRTypeListContext: 03221 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 03222 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 03223 case Declarator::TypeNameContext: 03224 case Declarator::CXXNewContext: 03225 case Declarator::AliasDeclContext: 03226 case Declarator::AliasTemplateContext: 03227 case Declarator::MemberContext: 03228 case Declarator::BlockContext: 03229 case Declarator::ForContext: 03230 case Declarator::ConditionContext: 03231 case Declarator::CXXCatchContext: 03232 case Declarator::ObjCCatchContext: 03233 case Declarator::BlockLiteralContext: 03234 case Declarator::LambdaExprContext: 03235 case Declarator::ConversionIdContext: 03236 case Declarator::TrailingReturnContext: 03237 case Declarator::TemplateTypeArgContext: 03238 // FIXME: We may want to allow parameter packs in block-literal contexts 03239 // in the future. 03240 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 03241 D.setEllipsisLoc(SourceLocation()); 03242 break; 03243 } 03244 } 03245 03246 if (T.isNull()) 03247 return Context.getNullTypeSourceInfo(); 03248 else if (D.isInvalidType()) 03249 return Context.getTrivialTypeSourceInfo(T); 03250 03251 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 03252 } 03253 03254 /// GetTypeForDeclarator - Convert the type for the specified 03255 /// declarator to Type instances. 03256 /// 03257 /// The result of this call will never be null, but the associated 03258 /// type may be a null type if there's an unrecoverable error. 03259 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 03260 // Determine the type of the declarator. Not all forms of declarator 03261 // have a type. 03262 03263 TypeProcessingState state(*this, D); 03264 03265 TypeSourceInfo *ReturnTypeInfo = nullptr; 03266 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 03267 if (T.isNull()) 03268 return Context.getNullTypeSourceInfo(); 03269 03270 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 03271 inferARCWriteback(state, T); 03272 03273 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 03274 } 03275 03276 static void transferARCOwnershipToDeclSpec(Sema &S, 03277 QualType &declSpecTy, 03278 Qualifiers::ObjCLifetime ownership) { 03279 if (declSpecTy->isObjCRetainableType() && 03280 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 03281 Qualifiers qs; 03282 qs.addObjCLifetime(ownership); 03283 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 03284 } 03285 } 03286 03287 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 03288 Qualifiers::ObjCLifetime ownership, 03289 unsigned chunkIndex) { 03290 Sema &S = state.getSema(); 03291 Declarator &D = state.getDeclarator(); 03292 03293 // Look for an explicit lifetime attribute. 03294 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 03295 for (const AttributeList *attr = chunk.getAttrs(); attr; 03296 attr = attr->getNext()) 03297 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 03298 return; 03299 03300 const char *attrStr = nullptr; 03301 switch (ownership) { 03302 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 03303 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 03304 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 03305 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 03306 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 03307 } 03308 03309 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 03310 Arg->Ident = &S.Context.Idents.get(attrStr); 03311 Arg->Loc = SourceLocation(); 03312 03313 ArgsUnion Args(Arg); 03314 03315 // If there wasn't one, add one (with an invalid source location 03316 // so that we don't make an AttributedType for it). 03317 AttributeList *attr = D.getAttributePool() 03318 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 03319 /*scope*/ nullptr, SourceLocation(), 03320 /*args*/ &Args, 1, AttributeList::AS_GNU); 03321 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 03322 03323 // TODO: mark whether we did this inference? 03324 } 03325 03326 /// \brief Used for transferring ownership in casts resulting in l-values. 03327 static void transferARCOwnership(TypeProcessingState &state, 03328 QualType &declSpecTy, 03329 Qualifiers::ObjCLifetime ownership) { 03330 Sema &S = state.getSema(); 03331 Declarator &D = state.getDeclarator(); 03332 03333 int inner = -1; 03334 bool hasIndirection = false; 03335 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 03336 DeclaratorChunk &chunk = D.getTypeObject(i); 03337 switch (chunk.Kind) { 03338 case DeclaratorChunk::Paren: 03339 // Ignore parens. 03340 break; 03341 03342 case DeclaratorChunk::Array: 03343 case DeclaratorChunk::Reference: 03344 case DeclaratorChunk::Pointer: 03345 if (inner != -1) 03346 hasIndirection = true; 03347 inner = i; 03348 break; 03349 03350 case DeclaratorChunk::BlockPointer: 03351 if (inner != -1) 03352 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 03353 return; 03354 03355 case DeclaratorChunk::Function: 03356 case DeclaratorChunk::MemberPointer: 03357 return; 03358 } 03359 } 03360 03361 if (inner == -1) 03362 return; 03363 03364 DeclaratorChunk &chunk = D.getTypeObject(inner); 03365 if (chunk.Kind == DeclaratorChunk::Pointer) { 03366 if (declSpecTy->isObjCRetainableType()) 03367 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 03368 if (declSpecTy->isObjCObjectType() && hasIndirection) 03369 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 03370 } else { 03371 assert(chunk.Kind == DeclaratorChunk::Array || 03372 chunk.Kind == DeclaratorChunk::Reference); 03373 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 03374 } 03375 } 03376 03377 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 03378 TypeProcessingState state(*this, D); 03379 03380 TypeSourceInfo *ReturnTypeInfo = nullptr; 03381 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 03382 if (declSpecTy.isNull()) 03383 return Context.getNullTypeSourceInfo(); 03384 03385 if (getLangOpts().ObjCAutoRefCount) { 03386 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 03387 if (ownership != Qualifiers::OCL_None) 03388 transferARCOwnership(state, declSpecTy, ownership); 03389 } 03390 03391 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 03392 } 03393 03394 /// Map an AttributedType::Kind to an AttributeList::Kind. 03395 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 03396 switch (kind) { 03397 case AttributedType::attr_address_space: 03398 return AttributeList::AT_AddressSpace; 03399 case AttributedType::attr_regparm: 03400 return AttributeList::AT_Regparm; 03401 case AttributedType::attr_vector_size: 03402 return AttributeList::AT_VectorSize; 03403 case AttributedType::attr_neon_vector_type: 03404 return AttributeList::AT_NeonVectorType; 03405 case AttributedType::attr_neon_polyvector_type: 03406 return AttributeList::AT_NeonPolyVectorType; 03407 case AttributedType::attr_objc_gc: 03408 return AttributeList::AT_ObjCGC; 03409 case AttributedType::attr_objc_ownership: 03410 return AttributeList::AT_ObjCOwnership; 03411 case AttributedType::attr_noreturn: 03412 return AttributeList::AT_NoReturn; 03413 case AttributedType::attr_cdecl: 03414 return AttributeList::AT_CDecl; 03415 case AttributedType::attr_fastcall: 03416 return AttributeList::AT_FastCall; 03417 case AttributedType::attr_stdcall: 03418 return AttributeList::AT_StdCall; 03419 case AttributedType::attr_thiscall: 03420 return AttributeList::AT_ThisCall; 03421 case AttributedType::attr_pascal: 03422 return AttributeList::AT_Pascal; 03423 case AttributedType::attr_vectorcall: 03424 return AttributeList::AT_VectorCall; 03425 case AttributedType::attr_pcs: 03426 case AttributedType::attr_pcs_vfp: 03427 return AttributeList::AT_Pcs; 03428 case AttributedType::attr_pnaclcall: 03429 return AttributeList::AT_PnaclCall; 03430 case AttributedType::attr_inteloclbicc: 03431 return AttributeList::AT_IntelOclBicc; 03432 case AttributedType::attr_ms_abi: 03433 return AttributeList::AT_MSABI; 03434 case AttributedType::attr_sysv_abi: 03435 return AttributeList::AT_SysVABI; 03436 case AttributedType::attr_ptr32: 03437 return AttributeList::AT_Ptr32; 03438 case AttributedType::attr_ptr64: 03439 return AttributeList::AT_Ptr64; 03440 case AttributedType::attr_sptr: 03441 return AttributeList::AT_SPtr; 03442 case AttributedType::attr_uptr: 03443 return AttributeList::AT_UPtr; 03444 } 03445 llvm_unreachable("unexpected attribute kind!"); 03446 } 03447 03448 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 03449 const AttributeList *attrs) { 03450 AttributedType::Kind kind = TL.getAttrKind(); 03451 03452 assert(attrs && "no type attributes in the expected location!"); 03453 AttributeList::Kind parsedKind = getAttrListKind(kind); 03454 while (attrs->getKind() != parsedKind) { 03455 attrs = attrs->getNext(); 03456 assert(attrs && "no matching attribute in expected location!"); 03457 } 03458 03459 TL.setAttrNameLoc(attrs->getLoc()); 03460 if (TL.hasAttrExprOperand()) { 03461 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 03462 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 03463 } else if (TL.hasAttrEnumOperand()) { 03464 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 03465 "unexpected attribute operand kind"); 03466 if (attrs->isArgIdent(0)) 03467 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 03468 else 03469 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 03470 } 03471 03472 // FIXME: preserve this information to here. 03473 if (TL.hasAttrOperand()) 03474 TL.setAttrOperandParensRange(SourceRange()); 03475 } 03476 03477 namespace { 03478 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 03479 ASTContext &Context; 03480 const DeclSpec &DS; 03481 03482 public: 03483 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 03484 : Context(Context), DS(DS) {} 03485 03486 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 03487 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 03488 Visit(TL.getModifiedLoc()); 03489 } 03490 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 03491 Visit(TL.getUnqualifiedLoc()); 03492 } 03493 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 03494 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 03495 } 03496 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 03497 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 03498 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 03499 // addition field. What we have is good enough for dispay of location 03500 // of 'fixit' on interface name. 03501 TL.setNameEndLoc(DS.getLocEnd()); 03502 } 03503 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 03504 // Handle the base type, which might not have been written explicitly. 03505 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 03506 TL.setHasBaseTypeAsWritten(false); 03507 TL.getBaseLoc().initialize(Context, SourceLocation()); 03508 } else { 03509 TL.setHasBaseTypeAsWritten(true); 03510 Visit(TL.getBaseLoc()); 03511 } 03512 03513 // Protocol qualifiers. 03514 if (DS.getProtocolQualifiers()) { 03515 assert(TL.getNumProtocols() > 0); 03516 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 03517 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 03518 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 03519 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 03520 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 03521 } else { 03522 assert(TL.getNumProtocols() == 0); 03523 TL.setLAngleLoc(SourceLocation()); 03524 TL.setRAngleLoc(SourceLocation()); 03525 } 03526 } 03527 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 03528 TL.setStarLoc(SourceLocation()); 03529 Visit(TL.getPointeeLoc()); 03530 } 03531 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 03532 TypeSourceInfo *TInfo = nullptr; 03533 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03534 03535 // If we got no declarator info from previous Sema routines, 03536 // just fill with the typespec loc. 03537 if (!TInfo) { 03538 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 03539 return; 03540 } 03541 03542 TypeLoc OldTL = TInfo->getTypeLoc(); 03543 if (TInfo->getType()->getAs<ElaboratedType>()) { 03544 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 03545 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 03546 .castAs<TemplateSpecializationTypeLoc>(); 03547 TL.copy(NamedTL); 03548 } else { 03549 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 03550 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 03551 } 03552 03553 } 03554 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 03555 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 03556 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 03557 TL.setParensRange(DS.getTypeofParensRange()); 03558 } 03559 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 03560 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 03561 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 03562 TL.setParensRange(DS.getTypeofParensRange()); 03563 assert(DS.getRepAsType()); 03564 TypeSourceInfo *TInfo = nullptr; 03565 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03566 TL.setUnderlyingTInfo(TInfo); 03567 } 03568 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 03569 // FIXME: This holds only because we only have one unary transform. 03570 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 03571 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 03572 TL.setParensRange(DS.getTypeofParensRange()); 03573 assert(DS.getRepAsType()); 03574 TypeSourceInfo *TInfo = nullptr; 03575 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03576 TL.setUnderlyingTInfo(TInfo); 03577 } 03578 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 03579 // By default, use the source location of the type specifier. 03580 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 03581 if (TL.needsExtraLocalData()) { 03582 // Set info for the written builtin specifiers. 03583 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 03584 // Try to have a meaningful source location. 03585 if (TL.getWrittenSignSpec() != TSS_unspecified) 03586 // Sign spec loc overrides the others (e.g., 'unsigned long'). 03587 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 03588 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 03589 // Width spec loc overrides type spec loc (e.g., 'short int'). 03590 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 03591 } 03592 } 03593 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 03594 ElaboratedTypeKeyword Keyword 03595 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 03596 if (DS.getTypeSpecType() == TST_typename) { 03597 TypeSourceInfo *TInfo = nullptr; 03598 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03599 if (TInfo) { 03600 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 03601 return; 03602 } 03603 } 03604 TL.setElaboratedKeywordLoc(Keyword != ETK_None 03605 ? DS.getTypeSpecTypeLoc() 03606 : SourceLocation()); 03607 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 03608 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 03609 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 03610 } 03611 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 03612 assert(DS.getTypeSpecType() == TST_typename); 03613 TypeSourceInfo *TInfo = nullptr; 03614 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03615 assert(TInfo); 03616 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 03617 } 03618 void VisitDependentTemplateSpecializationTypeLoc( 03619 DependentTemplateSpecializationTypeLoc TL) { 03620 assert(DS.getTypeSpecType() == TST_typename); 03621 TypeSourceInfo *TInfo = nullptr; 03622 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03623 assert(TInfo); 03624 TL.copy( 03625 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 03626 } 03627 void VisitTagTypeLoc(TagTypeLoc TL) { 03628 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 03629 } 03630 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 03631 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 03632 // or an _Atomic qualifier. 03633 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 03634 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 03635 TL.setParensRange(DS.getTypeofParensRange()); 03636 03637 TypeSourceInfo *TInfo = nullptr; 03638 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03639 assert(TInfo); 03640 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 03641 } else { 03642 TL.setKWLoc(DS.getAtomicSpecLoc()); 03643 // No parens, to indicate this was spelled as an _Atomic qualifier. 03644 TL.setParensRange(SourceRange()); 03645 Visit(TL.getValueLoc()); 03646 } 03647 } 03648 03649 void VisitTypeLoc(TypeLoc TL) { 03650 // FIXME: add other typespec types and change this to an assert. 03651 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 03652 } 03653 }; 03654 03655 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 03656 ASTContext &Context; 03657 const DeclaratorChunk &Chunk; 03658 03659 public: 03660 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 03661 : Context(Context), Chunk(Chunk) {} 03662 03663 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 03664 llvm_unreachable("qualified type locs not expected here!"); 03665 } 03666 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 03667 llvm_unreachable("decayed type locs not expected here!"); 03668 } 03669 03670 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 03671 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 03672 } 03673 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 03674 // nothing 03675 } 03676 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 03677 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 03678 TL.setCaretLoc(Chunk.Loc); 03679 } 03680 void VisitPointerTypeLoc(PointerTypeLoc TL) { 03681 assert(Chunk.Kind == DeclaratorChunk::Pointer); 03682 TL.setStarLoc(Chunk.Loc); 03683 } 03684 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 03685 assert(Chunk.Kind == DeclaratorChunk::Pointer); 03686 TL.setStarLoc(Chunk.Loc); 03687 } 03688 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 03689 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 03690 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 03691 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 03692 03693 const Type* ClsTy = TL.getClass(); 03694 QualType ClsQT = QualType(ClsTy, 0); 03695 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 03696 // Now copy source location info into the type loc component. 03697 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 03698 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 03699 case NestedNameSpecifier::Identifier: 03700 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 03701 { 03702 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 03703 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 03704 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 03705 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 03706 } 03707 break; 03708 03709 case NestedNameSpecifier::TypeSpec: 03710 case NestedNameSpecifier::TypeSpecWithTemplate: 03711 if (isa<ElaboratedType>(ClsTy)) { 03712 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 03713 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 03714 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 03715 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 03716 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 03717 } else { 03718 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 03719 } 03720 break; 03721 03722 case NestedNameSpecifier::Namespace: 03723 case NestedNameSpecifier::NamespaceAlias: 03724 case NestedNameSpecifier::Global: 03725 case NestedNameSpecifier::Super: 03726 llvm_unreachable("Nested-name-specifier must name a type"); 03727 } 03728 03729 // Finally fill in MemberPointerLocInfo fields. 03730 TL.setStarLoc(Chunk.Loc); 03731 TL.setClassTInfo(ClsTInfo); 03732 } 03733 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 03734 assert(Chunk.Kind == DeclaratorChunk::Reference); 03735 // 'Amp' is misleading: this might have been originally 03736 /// spelled with AmpAmp. 03737 TL.setAmpLoc(Chunk.Loc); 03738 } 03739 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 03740 assert(Chunk.Kind == DeclaratorChunk::Reference); 03741 assert(!Chunk.Ref.LValueRef); 03742 TL.setAmpAmpLoc(Chunk.Loc); 03743 } 03744 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 03745 assert(Chunk.Kind == DeclaratorChunk::Array); 03746 TL.setLBracketLoc(Chunk.Loc); 03747 TL.setRBracketLoc(Chunk.EndLoc); 03748 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 03749 } 03750 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 03751 assert(Chunk.Kind == DeclaratorChunk::Function); 03752 TL.setLocalRangeBegin(Chunk.Loc); 03753 TL.setLocalRangeEnd(Chunk.EndLoc); 03754 03755 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 03756 TL.setLParenLoc(FTI.getLParenLoc()); 03757 TL.setRParenLoc(FTI.getRParenLoc()); 03758 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 03759 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 03760 TL.setParam(tpi++, Param); 03761 } 03762 // FIXME: exception specs 03763 } 03764 void VisitParenTypeLoc(ParenTypeLoc TL) { 03765 assert(Chunk.Kind == DeclaratorChunk::Paren); 03766 TL.setLParenLoc(Chunk.Loc); 03767 TL.setRParenLoc(Chunk.EndLoc); 03768 } 03769 03770 void VisitTypeLoc(TypeLoc TL) { 03771 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 03772 } 03773 }; 03774 } 03775 03776 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 03777 SourceLocation Loc; 03778 switch (Chunk.Kind) { 03779 case DeclaratorChunk::Function: 03780 case DeclaratorChunk::Array: 03781 case DeclaratorChunk::Paren: 03782 llvm_unreachable("cannot be _Atomic qualified"); 03783 03784 case DeclaratorChunk::Pointer: 03785 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 03786 break; 03787 03788 case DeclaratorChunk::BlockPointer: 03789 case DeclaratorChunk::Reference: 03790 case DeclaratorChunk::MemberPointer: 03791 // FIXME: Provide a source location for the _Atomic keyword. 03792 break; 03793 } 03794 03795 ATL.setKWLoc(Loc); 03796 ATL.setParensRange(SourceRange()); 03797 } 03798 03799 /// \brief Create and instantiate a TypeSourceInfo with type source information. 03800 /// 03801 /// \param T QualType referring to the type as written in source code. 03802 /// 03803 /// \param ReturnTypeInfo For declarators whose return type does not show 03804 /// up in the normal place in the declaration specifiers (such as a C++ 03805 /// conversion function), this pointer will refer to a type source information 03806 /// for that return type. 03807 TypeSourceInfo * 03808 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 03809 TypeSourceInfo *ReturnTypeInfo) { 03810 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 03811 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 03812 03813 // Handle parameter packs whose type is a pack expansion. 03814 if (isa<PackExpansionType>(T)) { 03815 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 03816 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 03817 } 03818 03819 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 03820 // An AtomicTypeLoc might be produced by an atomic qualifier in this 03821 // declarator chunk. 03822 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 03823 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 03824 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 03825 } 03826 03827 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 03828 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 03829 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 03830 } 03831 03832 // FIXME: Ordering here? 03833 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 03834 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 03835 03836 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 03837 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 03838 } 03839 03840 // If we have different source information for the return type, use 03841 // that. This really only applies to C++ conversion functions. 03842 if (ReturnTypeInfo) { 03843 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 03844 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 03845 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 03846 } else { 03847 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 03848 } 03849 03850 return TInfo; 03851 } 03852 03853 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 03854 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 03855 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 03856 // and Sema during declaration parsing. Try deallocating/caching them when 03857 // it's appropriate, instead of allocating them and keeping them around. 03858 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 03859 TypeAlignment); 03860 new (LocT) LocInfoType(T, TInfo); 03861 assert(LocT->getTypeClass() != T->getTypeClass() && 03862 "LocInfoType's TypeClass conflicts with an existing Type class"); 03863 return ParsedType::make(QualType(LocT, 0)); 03864 } 03865 03866 void LocInfoType::getAsStringInternal(std::string &Str, 03867 const PrintingPolicy &Policy) const { 03868 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 03869 " was used directly instead of getting the QualType through" 03870 " GetTypeFromParser"); 03871 } 03872 03873 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 03874 // C99 6.7.6: Type names have no identifier. This is already validated by 03875 // the parser. 03876 assert(D.getIdentifier() == nullptr && 03877 "Type name should have no identifier!"); 03878 03879 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 03880 QualType T = TInfo->getType(); 03881 if (D.isInvalidType()) 03882 return true; 03883 03884 // Make sure there are no unused decl attributes on the declarator. 03885 // We don't want to do this for ObjC parameters because we're going 03886 // to apply them to the actual parameter declaration. 03887 // Likewise, we don't want to do this for alias declarations, because 03888 // we are actually going to build a declaration from this eventually. 03889 if (D.getContext() != Declarator::ObjCParameterContext && 03890 D.getContext() != Declarator::AliasDeclContext && 03891 D.getContext() != Declarator::AliasTemplateContext) 03892 checkUnusedDeclAttributes(D); 03893 03894 if (getLangOpts().CPlusPlus) { 03895 // Check that there are no default arguments (C++ only). 03896 CheckExtraCXXDefaultArguments(D); 03897 } 03898 03899 return CreateParsedType(T, TInfo); 03900 } 03901 03902 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 03903 QualType T = Context.getObjCInstanceType(); 03904 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 03905 return CreateParsedType(T, TInfo); 03906 } 03907 03908 03909 //===----------------------------------------------------------------------===// 03910 // Type Attribute Processing 03911 //===----------------------------------------------------------------------===// 03912 03913 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 03914 /// specified type. The attribute contains 1 argument, the id of the address 03915 /// space for the type. 03916 static void HandleAddressSpaceTypeAttribute(QualType &Type, 03917 const AttributeList &Attr, Sema &S){ 03918 03919 // If this type is already address space qualified, reject it. 03920 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 03921 // qualifiers for two or more different address spaces." 03922 if (Type.getAddressSpace()) { 03923 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 03924 Attr.setInvalid(); 03925 return; 03926 } 03927 03928 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 03929 // qualified by an address-space qualifier." 03930 if (Type->isFunctionType()) { 03931 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 03932 Attr.setInvalid(); 03933 return; 03934 } 03935 03936 unsigned ASIdx; 03937 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 03938 // Check the attribute arguments. 03939 if (Attr.getNumArgs() != 1) { 03940 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 03941 << Attr.getName() << 1; 03942 Attr.setInvalid(); 03943 return; 03944 } 03945 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 03946 llvm::APSInt addrSpace(32); 03947 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 03948 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 03949 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 03950 << Attr.getName() << AANT_ArgumentIntegerConstant 03951 << ASArgExpr->getSourceRange(); 03952 Attr.setInvalid(); 03953 return; 03954 } 03955 03956 // Bounds checking. 03957 if (addrSpace.isSigned()) { 03958 if (addrSpace.isNegative()) { 03959 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 03960 << ASArgExpr->getSourceRange(); 03961 Attr.setInvalid(); 03962 return; 03963 } 03964 addrSpace.setIsSigned(false); 03965 } 03966 llvm::APSInt max(addrSpace.getBitWidth()); 03967 max = Qualifiers::MaxAddressSpace; 03968 if (addrSpace > max) { 03969 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 03970 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange(); 03971 Attr.setInvalid(); 03972 return; 03973 } 03974 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 03975 } else { 03976 // The keyword-based type attributes imply which address space to use. 03977 switch (Attr.getKind()) { 03978 case AttributeList::AT_OpenCLGlobalAddressSpace: 03979 ASIdx = LangAS::opencl_global; break; 03980 case AttributeList::AT_OpenCLLocalAddressSpace: 03981 ASIdx = LangAS::opencl_local; break; 03982 case AttributeList::AT_OpenCLConstantAddressSpace: 03983 ASIdx = LangAS::opencl_constant; break; 03984 default: 03985 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace); 03986 ASIdx = 0; break; 03987 } 03988 } 03989 03990 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 03991 } 03992 03993 /// Does this type have a "direct" ownership qualifier? That is, 03994 /// is it written like "__strong id", as opposed to something like 03995 /// "typeof(foo)", where that happens to be strong? 03996 static bool hasDirectOwnershipQualifier(QualType type) { 03997 // Fast path: no qualifier at all. 03998 assert(type.getQualifiers().hasObjCLifetime()); 03999 04000 while (true) { 04001 // __strong id 04002 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 04003 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 04004 return true; 04005 04006 type = attr->getModifiedType(); 04007 04008 // X *__strong (...) 04009 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 04010 type = paren->getInnerType(); 04011 04012 // That's it for things we want to complain about. In particular, 04013 // we do not want to look through typedefs, typeof(expr), 04014 // typeof(type), or any other way that the type is somehow 04015 // abstracted. 04016 } else { 04017 04018 return false; 04019 } 04020 } 04021 } 04022 04023 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 04024 /// attribute on the specified type. 04025 /// 04026 /// Returns 'true' if the attribute was handled. 04027 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 04028 AttributeList &attr, 04029 QualType &type) { 04030 bool NonObjCPointer = false; 04031 04032 if (!type->isDependentType() && !type->isUndeducedType()) { 04033 if (const PointerType *ptr = type->getAs<PointerType>()) { 04034 QualType pointee = ptr->getPointeeType(); 04035 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 04036 return false; 04037 // It is important not to lose the source info that there was an attribute 04038 // applied to non-objc pointer. We will create an attributed type but 04039 // its type will be the same as the original type. 04040 NonObjCPointer = true; 04041 } else if (!type->isObjCRetainableType()) { 04042 return false; 04043 } 04044 04045 // Don't accept an ownership attribute in the declspec if it would 04046 // just be the return type of a block pointer. 04047 if (state.isProcessingDeclSpec()) { 04048 Declarator &D = state.getDeclarator(); 04049 if (maybeMovePastReturnType(D, D.getNumTypeObjects())) 04050 return false; 04051 } 04052 } 04053 04054 Sema &S = state.getSema(); 04055 SourceLocation AttrLoc = attr.getLoc(); 04056 if (AttrLoc.isMacroID()) 04057 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 04058 04059 if (!attr.isArgIdent(0)) { 04060 S.Diag(AttrLoc, diag::err_attribute_argument_type) 04061 << attr.getName() << AANT_ArgumentString; 04062 attr.setInvalid(); 04063 return true; 04064 } 04065 04066 // Consume lifetime attributes without further comment outside of 04067 // ARC mode. 04068 if (!S.getLangOpts().ObjCAutoRefCount) 04069 return true; 04070 04071 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 04072 Qualifiers::ObjCLifetime lifetime; 04073 if (II->isStr("none")) 04074 lifetime = Qualifiers::OCL_ExplicitNone; 04075 else if (II->isStr("strong")) 04076 lifetime = Qualifiers::OCL_Strong; 04077 else if (II->isStr("weak")) 04078 lifetime = Qualifiers::OCL_Weak; 04079 else if (II->isStr("autoreleasing")) 04080 lifetime = Qualifiers::OCL_Autoreleasing; 04081 else { 04082 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 04083 << attr.getName() << II; 04084 attr.setInvalid(); 04085 return true; 04086 } 04087 04088 SplitQualType underlyingType = type.split(); 04089 04090 // Check for redundant/conflicting ownership qualifiers. 04091 if (Qualifiers::ObjCLifetime previousLifetime 04092 = type.getQualifiers().getObjCLifetime()) { 04093 // If it's written directly, that's an error. 04094 if (hasDirectOwnershipQualifier(type)) { 04095 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 04096 << type; 04097 return true; 04098 } 04099 04100 // Otherwise, if the qualifiers actually conflict, pull sugar off 04101 // until we reach a type that is directly qualified. 04102 if (previousLifetime != lifetime) { 04103 // This should always terminate: the canonical type is 04104 // qualified, so some bit of sugar must be hiding it. 04105 while (!underlyingType.Quals.hasObjCLifetime()) { 04106 underlyingType = underlyingType.getSingleStepDesugaredType(); 04107 } 04108 underlyingType.Quals.removeObjCLifetime(); 04109 } 04110 } 04111 04112 underlyingType.Quals.addObjCLifetime(lifetime); 04113 04114 if (NonObjCPointer) { 04115 StringRef name = attr.getName()->getName(); 04116 switch (lifetime) { 04117 case Qualifiers::OCL_None: 04118 case Qualifiers::OCL_ExplicitNone: 04119 break; 04120 case Qualifiers::OCL_Strong: name = "__strong"; break; 04121 case Qualifiers::OCL_Weak: name = "__weak"; break; 04122 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 04123 } 04124 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 04125 << TDS_ObjCObjOrBlock << type; 04126 } 04127 04128 QualType origType = type; 04129 if (!NonObjCPointer) 04130 type = S.Context.getQualifiedType(underlyingType); 04131 04132 // If we have a valid source location for the attribute, use an 04133 // AttributedType instead. 04134 if (AttrLoc.isValid()) 04135 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 04136 origType, type); 04137 04138 // Forbid __weak if the runtime doesn't support it. 04139 if (lifetime == Qualifiers::OCL_Weak && 04140 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) { 04141 04142 // Actually, delay this until we know what we're parsing. 04143 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 04144 S.DelayedDiagnostics.add( 04145 sema::DelayedDiagnostic::makeForbiddenType( 04146 S.getSourceManager().getExpansionLoc(AttrLoc), 04147 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 04148 } else { 04149 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 04150 } 04151 04152 attr.setInvalid(); 04153 return true; 04154 } 04155 04156 // Forbid __weak for class objects marked as 04157 // objc_arc_weak_reference_unavailable 04158 if (lifetime == Qualifiers::OCL_Weak) { 04159 if (const ObjCObjectPointerType *ObjT = 04160 type->getAs<ObjCObjectPointerType>()) { 04161 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 04162 if (Class->isArcWeakrefUnavailable()) { 04163 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 04164 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 04165 diag::note_class_declared); 04166 } 04167 } 04168 } 04169 } 04170 04171 return true; 04172 } 04173 04174 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 04175 /// attribute on the specified type. Returns true to indicate that 04176 /// the attribute was handled, false to indicate that the type does 04177 /// not permit the attribute. 04178 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 04179 AttributeList &attr, 04180 QualType &type) { 04181 Sema &S = state.getSema(); 04182 04183 // Delay if this isn't some kind of pointer. 04184 if (!type->isPointerType() && 04185 !type->isObjCObjectPointerType() && 04186 !type->isBlockPointerType()) 04187 return false; 04188 04189 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 04190 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 04191 attr.setInvalid(); 04192 return true; 04193 } 04194 04195 // Check the attribute arguments. 04196 if (!attr.isArgIdent(0)) { 04197 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 04198 << attr.getName() << AANT_ArgumentString; 04199 attr.setInvalid(); 04200 return true; 04201 } 04202 Qualifiers::GC GCAttr; 04203 if (attr.getNumArgs() > 1) { 04204 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 04205 << attr.getName() << 1; 04206 attr.setInvalid(); 04207 return true; 04208 } 04209 04210 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 04211 if (II->isStr("weak")) 04212 GCAttr = Qualifiers::Weak; 04213 else if (II->isStr("strong")) 04214 GCAttr = Qualifiers::Strong; 04215 else { 04216 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 04217 << attr.getName() << II; 04218 attr.setInvalid(); 04219 return true; 04220 } 04221 04222 QualType origType = type; 04223 type = S.Context.getObjCGCQualType(origType, GCAttr); 04224 04225 // Make an attributed type to preserve the source information. 04226 if (attr.getLoc().isValid()) 04227 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 04228 origType, type); 04229 04230 return true; 04231 } 04232 04233 namespace { 04234 /// A helper class to unwrap a type down to a function for the 04235 /// purposes of applying attributes there. 04236 /// 04237 /// Use: 04238 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 04239 /// if (unwrapped.isFunctionType()) { 04240 /// const FunctionType *fn = unwrapped.get(); 04241 /// // change fn somehow 04242 /// T = unwrapped.wrap(fn); 04243 /// } 04244 struct FunctionTypeUnwrapper { 04245 enum WrapKind { 04246 Desugar, 04247 Parens, 04248 Pointer, 04249 BlockPointer, 04250 Reference, 04251 MemberPointer 04252 }; 04253 04254 QualType Original; 04255 const FunctionType *Fn; 04256 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 04257 04258 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 04259 while (true) { 04260 const Type *Ty = T.getTypePtr(); 04261 if (isa<FunctionType>(Ty)) { 04262 Fn = cast<FunctionType>(Ty); 04263 return; 04264 } else if (isa<ParenType>(Ty)) { 04265 T = cast<ParenType>(Ty)->getInnerType(); 04266 Stack.push_back(Parens); 04267 } else if (isa<PointerType>(Ty)) { 04268 T = cast<PointerType>(Ty)->getPointeeType(); 04269 Stack.push_back(Pointer); 04270 } else if (isa<BlockPointerType>(Ty)) { 04271 T = cast<BlockPointerType>(Ty)->getPointeeType(); 04272 Stack.push_back(BlockPointer); 04273 } else if (isa<MemberPointerType>(Ty)) { 04274 T = cast<MemberPointerType>(Ty)->getPointeeType(); 04275 Stack.push_back(MemberPointer); 04276 } else if (isa<ReferenceType>(Ty)) { 04277 T = cast<ReferenceType>(Ty)->getPointeeType(); 04278 Stack.push_back(Reference); 04279 } else { 04280 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 04281 if (Ty == DTy) { 04282 Fn = nullptr; 04283 return; 04284 } 04285 04286 T = QualType(DTy, 0); 04287 Stack.push_back(Desugar); 04288 } 04289 } 04290 } 04291 04292 bool isFunctionType() const { return (Fn != nullptr); } 04293 const FunctionType *get() const { return Fn; } 04294 04295 QualType wrap(Sema &S, const FunctionType *New) { 04296 // If T wasn't modified from the unwrapped type, do nothing. 04297 if (New == get()) return Original; 04298 04299 Fn = New; 04300 return wrap(S.Context, Original, 0); 04301 } 04302 04303 private: 04304 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 04305 if (I == Stack.size()) 04306 return C.getQualifiedType(Fn, Old.getQualifiers()); 04307 04308 // Build up the inner type, applying the qualifiers from the old 04309 // type to the new type. 04310 SplitQualType SplitOld = Old.split(); 04311 04312 // As a special case, tail-recurse if there are no qualifiers. 04313 if (SplitOld.Quals.empty()) 04314 return wrap(C, SplitOld.Ty, I); 04315 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 04316 } 04317 04318 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 04319 if (I == Stack.size()) return QualType(Fn, 0); 04320 04321 switch (static_cast<WrapKind>(Stack[I++])) { 04322 case Desugar: 04323 // This is the point at which we potentially lose source 04324 // information. 04325 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 04326 04327 case Parens: { 04328 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 04329 return C.getParenType(New); 04330 } 04331 04332 case Pointer: { 04333 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 04334 return C.getPointerType(New); 04335 } 04336 04337 case BlockPointer: { 04338 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 04339 return C.getBlockPointerType(New); 04340 } 04341 04342 case MemberPointer: { 04343 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 04344 QualType New = wrap(C, OldMPT->getPointeeType(), I); 04345 return C.getMemberPointerType(New, OldMPT->getClass()); 04346 } 04347 04348 case Reference: { 04349 const ReferenceType *OldRef = cast<ReferenceType>(Old); 04350 QualType New = wrap(C, OldRef->getPointeeType(), I); 04351 if (isa<LValueReferenceType>(OldRef)) 04352 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 04353 else 04354 return C.getRValueReferenceType(New); 04355 } 04356 } 04357 04358 llvm_unreachable("unknown wrapping kind"); 04359 } 04360 }; 04361 } 04362 04363 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 04364 AttributeList &Attr, 04365 QualType &Type) { 04366 Sema &S = State.getSema(); 04367 04368 AttributeList::Kind Kind = Attr.getKind(); 04369 QualType Desugared = Type; 04370 const AttributedType *AT = dyn_cast<AttributedType>(Type); 04371 while (AT) { 04372 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 04373 04374 // You cannot specify duplicate type attributes, so if the attribute has 04375 // already been applied, flag it. 04376 if (getAttrListKind(CurAttrKind) == Kind) { 04377 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 04378 << Attr.getName(); 04379 return true; 04380 } 04381 04382 // You cannot have both __sptr and __uptr on the same type, nor can you 04383 // have __ptr32 and __ptr64. 04384 if ((CurAttrKind == AttributedType::attr_ptr32 && 04385 Kind == AttributeList::AT_Ptr64) || 04386 (CurAttrKind == AttributedType::attr_ptr64 && 04387 Kind == AttributeList::AT_Ptr32)) { 04388 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 04389 << "'__ptr32'" << "'__ptr64'"; 04390 return true; 04391 } else if ((CurAttrKind == AttributedType::attr_sptr && 04392 Kind == AttributeList::AT_UPtr) || 04393 (CurAttrKind == AttributedType::attr_uptr && 04394 Kind == AttributeList::AT_SPtr)) { 04395 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 04396 << "'__sptr'" << "'__uptr'"; 04397 return true; 04398 } 04399 04400 Desugared = AT->getEquivalentType(); 04401 AT = dyn_cast<AttributedType>(Desugared); 04402 } 04403 04404 // Pointer type qualifiers can only operate on pointer types, but not 04405 // pointer-to-member types. 04406 if (!isa<PointerType>(Desugared)) { 04407 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ? 04408 diag::err_attribute_no_member_pointers : 04409 diag::err_attribute_pointers_only) << Attr.getName(); 04410 return true; 04411 } 04412 04413 AttributedType::Kind TAK; 04414 switch (Kind) { 04415 default: llvm_unreachable("Unknown attribute kind"); 04416 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 04417 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 04418 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 04419 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 04420 } 04421 04422 Type = S.Context.getAttributedType(TAK, Type, Type); 04423 return false; 04424 } 04425 04426 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 04427 assert(!Attr.isInvalid()); 04428 switch (Attr.getKind()) { 04429 default: 04430 llvm_unreachable("not a calling convention attribute"); 04431 case AttributeList::AT_CDecl: 04432 return AttributedType::attr_cdecl; 04433 case AttributeList::AT_FastCall: 04434 return AttributedType::attr_fastcall; 04435 case AttributeList::AT_StdCall: 04436 return AttributedType::attr_stdcall; 04437 case AttributeList::AT_ThisCall: 04438 return AttributedType::attr_thiscall; 04439 case AttributeList::AT_Pascal: 04440 return AttributedType::attr_pascal; 04441 case AttributeList::AT_VectorCall: 04442 return AttributedType::attr_vectorcall; 04443 case AttributeList::AT_Pcs: { 04444 // The attribute may have had a fixit applied where we treated an 04445 // identifier as a string literal. The contents of the string are valid, 04446 // but the form may not be. 04447 StringRef Str; 04448 if (Attr.isArgExpr(0)) 04449 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 04450 else 04451 Str = Attr.getArgAsIdent(0)->Ident->getName(); 04452 return llvm::StringSwitch<AttributedType::Kind>(Str) 04453 .Case("aapcs", AttributedType::attr_pcs) 04454 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 04455 } 04456 case AttributeList::AT_PnaclCall: 04457 return AttributedType::attr_pnaclcall; 04458 case AttributeList::AT_IntelOclBicc: 04459 return AttributedType::attr_inteloclbicc; 04460 case AttributeList::AT_MSABI: 04461 return AttributedType::attr_ms_abi; 04462 case AttributeList::AT_SysVABI: 04463 return AttributedType::attr_sysv_abi; 04464 } 04465 llvm_unreachable("unexpected attribute kind!"); 04466 } 04467 04468 /// Process an individual function attribute. Returns true to 04469 /// indicate that the attribute was handled, false if it wasn't. 04470 static bool handleFunctionTypeAttr(TypeProcessingState &state, 04471 AttributeList &attr, 04472 QualType &type) { 04473 Sema &S = state.getSema(); 04474 04475 FunctionTypeUnwrapper unwrapped(S, type); 04476 04477 if (attr.getKind() == AttributeList::AT_NoReturn) { 04478 if (S.CheckNoReturnAttr(attr)) 04479 return true; 04480 04481 // Delay if this is not a function type. 04482 if (!unwrapped.isFunctionType()) 04483 return false; 04484 04485 // Otherwise we can process right away. 04486 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 04487 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 04488 return true; 04489 } 04490 04491 // ns_returns_retained is not always a type attribute, but if we got 04492 // here, we're treating it as one right now. 04493 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 04494 assert(S.getLangOpts().ObjCAutoRefCount && 04495 "ns_returns_retained treated as type attribute in non-ARC"); 04496 if (attr.getNumArgs()) return true; 04497 04498 // Delay if this is not a function type. 04499 if (!unwrapped.isFunctionType()) 04500 return false; 04501 04502 FunctionType::ExtInfo EI 04503 = unwrapped.get()->getExtInfo().withProducesResult(true); 04504 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 04505 return true; 04506 } 04507 04508 if (attr.getKind() == AttributeList::AT_Regparm) { 04509 unsigned value; 04510 if (S.CheckRegparmAttr(attr, value)) 04511 return true; 04512 04513 // Delay if this is not a function type. 04514 if (!unwrapped.isFunctionType()) 04515 return false; 04516 04517 // Diagnose regparm with fastcall. 04518 const FunctionType *fn = unwrapped.get(); 04519 CallingConv CC = fn->getCallConv(); 04520 if (CC == CC_X86FastCall) { 04521 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 04522 << FunctionType::getNameForCallConv(CC) 04523 << "regparm"; 04524 attr.setInvalid(); 04525 return true; 04526 } 04527 04528 FunctionType::ExtInfo EI = 04529 unwrapped.get()->getExtInfo().withRegParm(value); 04530 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 04531 return true; 04532 } 04533 04534 // Delay if the type didn't work out to a function. 04535 if (!unwrapped.isFunctionType()) return false; 04536 04537 // Otherwise, a calling convention. 04538 CallingConv CC; 04539 if (S.CheckCallingConvAttr(attr, CC)) 04540 return true; 04541 04542 const FunctionType *fn = unwrapped.get(); 04543 CallingConv CCOld = fn->getCallConv(); 04544 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 04545 04546 if (CCOld != CC) { 04547 // Error out on when there's already an attribute on the type 04548 // and the CCs don't match. 04549 const AttributedType *AT = S.getCallingConvAttributedType(type); 04550 if (AT && AT->getAttrKind() != CCAttrKind) { 04551 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 04552 << FunctionType::getNameForCallConv(CC) 04553 << FunctionType::getNameForCallConv(CCOld); 04554 attr.setInvalid(); 04555 return true; 04556 } 04557 } 04558 04559 // Diagnose use of callee-cleanup calling convention on variadic functions. 04560 if (!supportsVariadicCall(CC)) { 04561 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 04562 if (FnP && FnP->isVariadic()) { 04563 unsigned DiagID = diag::err_cconv_varargs; 04564 // stdcall and fastcall are ignored with a warning for GCC and MS 04565 // compatibility. 04566 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 04567 DiagID = diag::warn_cconv_varargs; 04568 04569 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 04570 attr.setInvalid(); 04571 return true; 04572 } 04573 } 04574 04575 // Also diagnose fastcall with regparm. 04576 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 04577 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 04578 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 04579 attr.setInvalid(); 04580 return true; 04581 } 04582 04583 // Modify the CC from the wrapped function type, wrap it all back, and then 04584 // wrap the whole thing in an AttributedType as written. The modified type 04585 // might have a different CC if we ignored the attribute. 04586 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 04587 QualType Equivalent = 04588 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 04589 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 04590 return true; 04591 } 04592 04593 bool Sema::hasExplicitCallingConv(QualType &T) { 04594 QualType R = T.IgnoreParens(); 04595 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 04596 if (AT->isCallingConv()) 04597 return true; 04598 R = AT->getModifiedType().IgnoreParens(); 04599 } 04600 return false; 04601 } 04602 04603 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) { 04604 FunctionTypeUnwrapper Unwrapped(*this, T); 04605 const FunctionType *FT = Unwrapped.get(); 04606 bool IsVariadic = (isa<FunctionProtoType>(FT) && 04607 cast<FunctionProtoType>(FT)->isVariadic()); 04608 04609 // Only adjust types with the default convention. For example, on Windows we 04610 // should adjust a __cdecl type to __thiscall for instance methods, and a 04611 // __thiscall type to __cdecl for static methods. 04612 CallingConv CurCC = FT->getCallConv(); 04613 CallingConv FromCC = 04614 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 04615 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 04616 if (CurCC != FromCC || FromCC == ToCC) 04617 return; 04618 04619 if (hasExplicitCallingConv(T)) 04620 return; 04621 04622 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 04623 QualType Wrapped = Unwrapped.wrap(*this, FT); 04624 T = Context.getAdjustedType(T, Wrapped); 04625 } 04626 04627 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 04628 /// and float scalars, although arrays, pointers, and function return values are 04629 /// allowed in conjunction with this construct. Aggregates with this attribute 04630 /// are invalid, even if they are of the same size as a corresponding scalar. 04631 /// The raw attribute should contain precisely 1 argument, the vector size for 04632 /// the variable, measured in bytes. If curType and rawAttr are well formed, 04633 /// this routine will return a new vector type. 04634 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 04635 Sema &S) { 04636 // Check the attribute arguments. 04637 if (Attr.getNumArgs() != 1) { 04638 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 04639 << Attr.getName() << 1; 04640 Attr.setInvalid(); 04641 return; 04642 } 04643 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 04644 llvm::APSInt vecSize(32); 04645 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 04646 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 04647 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 04648 << Attr.getName() << AANT_ArgumentIntegerConstant 04649 << sizeExpr->getSourceRange(); 04650 Attr.setInvalid(); 04651 return; 04652 } 04653 // The base type must be integer (not Boolean or enumeration) or float, and 04654 // can't already be a vector. 04655 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 04656 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 04657 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 04658 Attr.setInvalid(); 04659 return; 04660 } 04661 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 04662 // vecSize is specified in bytes - convert to bits. 04663 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 04664 04665 // the vector size needs to be an integral multiple of the type size. 04666 if (vectorSize % typeSize) { 04667 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 04668 << sizeExpr->getSourceRange(); 04669 Attr.setInvalid(); 04670 return; 04671 } 04672 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 04673 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 04674 << sizeExpr->getSourceRange(); 04675 Attr.setInvalid(); 04676 return; 04677 } 04678 if (vectorSize == 0) { 04679 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 04680 << sizeExpr->getSourceRange(); 04681 Attr.setInvalid(); 04682 return; 04683 } 04684 04685 // Success! Instantiate the vector type, the number of elements is > 0, and 04686 // not required to be a power of 2, unlike GCC. 04687 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 04688 VectorType::GenericVector); 04689 } 04690 04691 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 04692 /// a type. 04693 static void HandleExtVectorTypeAttr(QualType &CurType, 04694 const AttributeList &Attr, 04695 Sema &S) { 04696 // check the attribute arguments. 04697 if (Attr.getNumArgs() != 1) { 04698 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 04699 << Attr.getName() << 1; 04700 return; 04701 } 04702 04703 Expr *sizeExpr; 04704 04705 // Special case where the argument is a template id. 04706 if (Attr.isArgIdent(0)) { 04707 CXXScopeSpec SS; 04708 SourceLocation TemplateKWLoc; 04709 UnqualifiedId id; 04710 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 04711 04712 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 04713 id, false, false); 04714 if (Size.isInvalid()) 04715 return; 04716 04717 sizeExpr = Size.get(); 04718 } else { 04719 sizeExpr = Attr.getArgAsExpr(0); 04720 } 04721 04722 // Create the vector type. 04723 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 04724 if (!T.isNull()) 04725 CurType = T; 04726 } 04727 04728 static bool isPermittedNeonBaseType(QualType &Ty, 04729 VectorType::VectorKind VecKind, Sema &S) { 04730 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 04731 if (!BTy) 04732 return false; 04733 04734 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 04735 04736 // Signed poly is mathematically wrong, but has been baked into some ABIs by 04737 // now. 04738 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 04739 Triple.getArch() == llvm::Triple::aarch64_be; 04740 if (VecKind == VectorType::NeonPolyVector) { 04741 if (IsPolyUnsigned) { 04742 // AArch64 polynomial vectors are unsigned and support poly64. 04743 return BTy->getKind() == BuiltinType::UChar || 04744 BTy->getKind() == BuiltinType::UShort || 04745 BTy->getKind() == BuiltinType::ULong || 04746 BTy->getKind() == BuiltinType::ULongLong; 04747 } else { 04748 // AArch32 polynomial vector are signed. 04749 return BTy->getKind() == BuiltinType::SChar || 04750 BTy->getKind() == BuiltinType::Short; 04751 } 04752 } 04753 04754 // Non-polynomial vector types: the usual suspects are allowed, as well as 04755 // float64_t on AArch64. 04756 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 04757 Triple.getArch() == llvm::Triple::aarch64_be; 04758 04759 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 04760 return true; 04761 04762 return BTy->getKind() == BuiltinType::SChar || 04763 BTy->getKind() == BuiltinType::UChar || 04764 BTy->getKind() == BuiltinType::Short || 04765 BTy->getKind() == BuiltinType::UShort || 04766 BTy->getKind() == BuiltinType::Int || 04767 BTy->getKind() == BuiltinType::UInt || 04768 BTy->getKind() == BuiltinType::Long || 04769 BTy->getKind() == BuiltinType::ULong || 04770 BTy->getKind() == BuiltinType::LongLong || 04771 BTy->getKind() == BuiltinType::ULongLong || 04772 BTy->getKind() == BuiltinType::Float || 04773 BTy->getKind() == BuiltinType::Half; 04774 } 04775 04776 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 04777 /// "neon_polyvector_type" attributes are used to create vector types that 04778 /// are mangled according to ARM's ABI. Otherwise, these types are identical 04779 /// to those created with the "vector_size" attribute. Unlike "vector_size" 04780 /// the argument to these Neon attributes is the number of vector elements, 04781 /// not the vector size in bytes. The vector width and element type must 04782 /// match one of the standard Neon vector types. 04783 static void HandleNeonVectorTypeAttr(QualType& CurType, 04784 const AttributeList &Attr, Sema &S, 04785 VectorType::VectorKind VecKind) { 04786 // Target must have NEON 04787 if (!S.Context.getTargetInfo().hasFeature("neon")) { 04788 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 04789 Attr.setInvalid(); 04790 return; 04791 } 04792 // Check the attribute arguments. 04793 if (Attr.getNumArgs() != 1) { 04794 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 04795 << Attr.getName() << 1; 04796 Attr.setInvalid(); 04797 return; 04798 } 04799 // The number of elements must be an ICE. 04800 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 04801 llvm::APSInt numEltsInt(32); 04802 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 04803 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 04804 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 04805 << Attr.getName() << AANT_ArgumentIntegerConstant 04806 << numEltsExpr->getSourceRange(); 04807 Attr.setInvalid(); 04808 return; 04809 } 04810 // Only certain element types are supported for Neon vectors. 04811 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 04812 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 04813 Attr.setInvalid(); 04814 return; 04815 } 04816 04817 // The total size of the vector must be 64 or 128 bits. 04818 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 04819 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 04820 unsigned vecSize = typeSize * numElts; 04821 if (vecSize != 64 && vecSize != 128) { 04822 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 04823 Attr.setInvalid(); 04824 return; 04825 } 04826 04827 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 04828 } 04829 04830 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 04831 TypeAttrLocation TAL, AttributeList *attrs) { 04832 // Scan through and apply attributes to this type where it makes sense. Some 04833 // attributes (such as __address_space__, __vector_size__, etc) apply to the 04834 // type, but others can be present in the type specifiers even though they 04835 // apply to the decl. Here we apply type attributes and ignore the rest. 04836 04837 AttributeList *next; 04838 do { 04839 AttributeList &attr = *attrs; 04840 next = attr.getNext(); 04841 04842 // Skip attributes that were marked to be invalid. 04843 if (attr.isInvalid()) 04844 continue; 04845 04846 if (attr.isCXX11Attribute()) { 04847 // [[gnu::...]] attributes are treated as declaration attributes, so may 04848 // not appertain to a DeclaratorChunk, even if we handle them as type 04849 // attributes. 04850 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 04851 if (TAL == TAL_DeclChunk) { 04852 state.getSema().Diag(attr.getLoc(), 04853 diag::warn_cxx11_gnu_attribute_on_type) 04854 << attr.getName(); 04855 continue; 04856 } 04857 } else if (TAL != TAL_DeclChunk) { 04858 // Otherwise, only consider type processing for a C++11 attribute if 04859 // it's actually been applied to a type. 04860 continue; 04861 } 04862 } 04863 04864 // If this is an attribute we can handle, do so now, 04865 // otherwise, add it to the FnAttrs list for rechaining. 04866 switch (attr.getKind()) { 04867 default: 04868 // A C++11 attribute on a declarator chunk must appertain to a type. 04869 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 04870 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 04871 << attr.getName(); 04872 attr.setUsedAsTypeAttr(); 04873 } 04874 break; 04875 04876 case AttributeList::UnknownAttribute: 04877 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 04878 state.getSema().Diag(attr.getLoc(), 04879 diag::warn_unknown_attribute_ignored) 04880 << attr.getName(); 04881 break; 04882 04883 case AttributeList::IgnoredAttribute: 04884 break; 04885 04886 case AttributeList::AT_MayAlias: 04887 // FIXME: This attribute needs to actually be handled, but if we ignore 04888 // it it breaks large amounts of Linux software. 04889 attr.setUsedAsTypeAttr(); 04890 break; 04891 case AttributeList::AT_OpenCLPrivateAddressSpace: 04892 case AttributeList::AT_OpenCLGlobalAddressSpace: 04893 case AttributeList::AT_OpenCLLocalAddressSpace: 04894 case AttributeList::AT_OpenCLConstantAddressSpace: 04895 case AttributeList::AT_AddressSpace: 04896 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 04897 attr.setUsedAsTypeAttr(); 04898 break; 04899 OBJC_POINTER_TYPE_ATTRS_CASELIST: 04900 if (!handleObjCPointerTypeAttr(state, attr, type)) 04901 distributeObjCPointerTypeAttr(state, attr, type); 04902 attr.setUsedAsTypeAttr(); 04903 break; 04904 case AttributeList::AT_VectorSize: 04905 HandleVectorSizeAttr(type, attr, state.getSema()); 04906 attr.setUsedAsTypeAttr(); 04907 break; 04908 case AttributeList::AT_ExtVectorType: 04909 HandleExtVectorTypeAttr(type, attr, state.getSema()); 04910 attr.setUsedAsTypeAttr(); 04911 break; 04912 case AttributeList::AT_NeonVectorType: 04913 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 04914 VectorType::NeonVector); 04915 attr.setUsedAsTypeAttr(); 04916 break; 04917 case AttributeList::AT_NeonPolyVectorType: 04918 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 04919 VectorType::NeonPolyVector); 04920 attr.setUsedAsTypeAttr(); 04921 break; 04922 case AttributeList::AT_OpenCLImageAccess: 04923 // FIXME: there should be some type checking happening here, I would 04924 // imagine, but the original handler's checking was entirely superfluous. 04925 attr.setUsedAsTypeAttr(); 04926 break; 04927 04928 MS_TYPE_ATTRS_CASELIST: 04929 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 04930 attr.setUsedAsTypeAttr(); 04931 break; 04932 04933 case AttributeList::AT_NSReturnsRetained: 04934 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 04935 break; 04936 // fallthrough into the function attrs 04937 04938 FUNCTION_TYPE_ATTRS_CASELIST: 04939 attr.setUsedAsTypeAttr(); 04940 04941 // Never process function type attributes as part of the 04942 // declaration-specifiers. 04943 if (TAL == TAL_DeclSpec) 04944 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 04945 04946 // Otherwise, handle the possible delays. 04947 else if (!handleFunctionTypeAttr(state, attr, type)) 04948 distributeFunctionTypeAttr(state, attr, type); 04949 break; 04950 } 04951 } while ((attrs = next)); 04952 } 04953 04954 /// \brief Ensure that the type of the given expression is complete. 04955 /// 04956 /// This routine checks whether the expression \p E has a complete type. If the 04957 /// expression refers to an instantiable construct, that instantiation is 04958 /// performed as needed to complete its type. Furthermore 04959 /// Sema::RequireCompleteType is called for the expression's type (or in the 04960 /// case of a reference type, the referred-to type). 04961 /// 04962 /// \param E The expression whose type is required to be complete. 04963 /// \param Diagnoser The object that will emit a diagnostic if the type is 04964 /// incomplete. 04965 /// 04966 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 04967 /// otherwise. 04968 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){ 04969 QualType T = E->getType(); 04970 04971 // Fast path the case where the type is already complete. 04972 if (!T->isIncompleteType()) 04973 // FIXME: The definition might not be visible. 04974 return false; 04975 04976 // Incomplete array types may be completed by the initializer attached to 04977 // their definitions. For static data members of class templates and for 04978 // variable templates, we need to instantiate the definition to get this 04979 // initializer and complete the type. 04980 if (T->isIncompleteArrayType()) { 04981 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 04982 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 04983 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 04984 SourceLocation PointOfInstantiation = E->getExprLoc(); 04985 04986 if (MemberSpecializationInfo *MSInfo = 04987 Var->getMemberSpecializationInfo()) { 04988 // If we don't already have a point of instantiation, this is it. 04989 if (MSInfo->getPointOfInstantiation().isInvalid()) { 04990 MSInfo->setPointOfInstantiation(PointOfInstantiation); 04991 04992 // This is a modification of an existing AST node. Notify 04993 // listeners. 04994 if (ASTMutationListener *L = getASTMutationListener()) 04995 L->StaticDataMemberInstantiated(Var); 04996 } 04997 } else { 04998 VarTemplateSpecializationDecl *VarSpec = 04999 cast<VarTemplateSpecializationDecl>(Var); 05000 if (VarSpec->getPointOfInstantiation().isInvalid()) 05001 VarSpec->setPointOfInstantiation(PointOfInstantiation); 05002 } 05003 05004 InstantiateVariableDefinition(PointOfInstantiation, Var); 05005 05006 // Update the type to the newly instantiated definition's type both 05007 // here and within the expression. 05008 if (VarDecl *Def = Var->getDefinition()) { 05009 DRE->setDecl(Def); 05010 T = Def->getType(); 05011 DRE->setType(T); 05012 E->setType(T); 05013 } 05014 05015 // We still go on to try to complete the type independently, as it 05016 // may also require instantiations or diagnostics if it remains 05017 // incomplete. 05018 } 05019 } 05020 } 05021 } 05022 05023 // FIXME: Are there other cases which require instantiating something other 05024 // than the type to complete the type of an expression? 05025 05026 // Look through reference types and complete the referred type. 05027 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 05028 T = Ref->getPointeeType(); 05029 05030 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 05031 } 05032 05033 namespace { 05034 struct TypeDiagnoserDiag : Sema::TypeDiagnoser { 05035 unsigned DiagID; 05036 05037 TypeDiagnoserDiag(unsigned DiagID) 05038 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {} 05039 05040 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 05041 if (Suppressed) return; 05042 S.Diag(Loc, DiagID) << T; 05043 } 05044 }; 05045 } 05046 05047 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 05048 TypeDiagnoserDiag Diagnoser(DiagID); 05049 return RequireCompleteExprType(E, Diagnoser); 05050 } 05051 05052 /// @brief Ensure that the type T is a complete type. 05053 /// 05054 /// This routine checks whether the type @p T is complete in any 05055 /// context where a complete type is required. If @p T is a complete 05056 /// type, returns false. If @p T is a class template specialization, 05057 /// this routine then attempts to perform class template 05058 /// instantiation. If instantiation fails, or if @p T is incomplete 05059 /// and cannot be completed, issues the diagnostic @p diag (giving it 05060 /// the type @p T) and returns true. 05061 /// 05062 /// @param Loc The location in the source that the incomplete type 05063 /// diagnostic should refer to. 05064 /// 05065 /// @param T The type that this routine is examining for completeness. 05066 /// 05067 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 05068 /// @c false otherwise. 05069 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 05070 TypeDiagnoser &Diagnoser) { 05071 if (RequireCompleteTypeImpl(Loc, T, Diagnoser)) 05072 return true; 05073 if (const TagType *Tag = T->getAs<TagType>()) { 05074 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 05075 Tag->getDecl()->setCompleteDefinitionRequired(); 05076 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 05077 } 05078 } 05079 return false; 05080 } 05081 05082 /// \brief Determine whether there is any declaration of \p D that was ever a 05083 /// definition (perhaps before module merging) and is currently visible. 05084 /// \param D The definition of the entity. 05085 /// \param Suggested Filled in with the declaration that should be made visible 05086 /// in order to provide a definition of this entity. 05087 static bool hasVisibleDefinition(Sema &S, NamedDecl *D, NamedDecl **Suggested) { 05088 // Easy case: if we don't have modules, all declarations are visible. 05089 if (!S.getLangOpts().Modules) 05090 return true; 05091 05092 // If this definition was instantiated from a template, map back to the 05093 // pattern from which it was instantiated. 05094 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 05095 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 05096 RD = Pattern; 05097 D = RD->getDefinition(); 05098 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 05099 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 05100 ED = NewED; 05101 if (ED->isFixed()) { 05102 // If the enum has a fixed underlying type, any declaration of it will do. 05103 *Suggested = nullptr; 05104 for (auto *Redecl : ED->redecls()) { 05105 if (LookupResult::isVisible(S, Redecl)) 05106 return true; 05107 if (Redecl->isThisDeclarationADefinition() || 05108 (Redecl->isCanonicalDecl() && !*Suggested)) 05109 *Suggested = Redecl; 05110 } 05111 return false; 05112 } 05113 D = ED->getDefinition(); 05114 } 05115 assert(D && "missing definition for pattern of instantiated definition"); 05116 05117 // FIXME: If we merged any other decl into D, and that declaration is visible, 05118 // then we should consider a definition to be visible. 05119 *Suggested = D; 05120 return LookupResult::isVisible(S, D); 05121 } 05122 05123 /// Locks in the inheritance model for the given class and all of its bases. 05124 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 05125 RD = RD->getMostRecentDecl(); 05126 if (!RD->hasAttr<MSInheritanceAttr>()) { 05127 MSInheritanceAttr::Spelling IM; 05128 05129 switch (S.MSPointerToMemberRepresentationMethod) { 05130 case LangOptions::PPTMK_BestCase: 05131 IM = RD->calculateInheritanceModel(); 05132 break; 05133 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 05134 IM = MSInheritanceAttr::Keyword_single_inheritance; 05135 break; 05136 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 05137 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 05138 break; 05139 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 05140 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 05141 break; 05142 } 05143 05144 RD->addAttr(MSInheritanceAttr::CreateImplicit( 05145 S.getASTContext(), IM, 05146 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 05147 LangOptions::PPTMK_BestCase, 05148 S.ImplicitMSInheritanceAttrLoc.isValid() 05149 ? S.ImplicitMSInheritanceAttrLoc 05150 : RD->getSourceRange())); 05151 } 05152 } 05153 05154 /// \brief The implementation of RequireCompleteType 05155 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 05156 TypeDiagnoser &Diagnoser) { 05157 // FIXME: Add this assertion to make sure we always get instantiation points. 05158 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 05159 // FIXME: Add this assertion to help us flush out problems with 05160 // checking for dependent types and type-dependent expressions. 05161 // 05162 // assert(!T->isDependentType() && 05163 // "Can't ask whether a dependent type is complete"); 05164 05165 // If we have a complete type, we're done. 05166 NamedDecl *Def = nullptr; 05167 if (!T->isIncompleteType(&Def)) { 05168 // If we know about the definition but it is not visible, complain. 05169 NamedDecl *SuggestedDef = nullptr; 05170 if (!Diagnoser.Suppressed && Def && 05171 !hasVisibleDefinition(*this, Def, &SuggestedDef)) { 05172 // Suppress this error outside of a SFINAE context if we've already 05173 // emitted the error once for this type. There's no usefulness in 05174 // repeating the diagnostic. 05175 // FIXME: Add a Fix-It that imports the corresponding module or includes 05176 // the header. 05177 Module *Owner = SuggestedDef->getOwningModule(); 05178 Diag(Loc, diag::err_module_private_definition) 05179 << T << Owner->getFullModuleName(); 05180 Diag(SuggestedDef->getLocation(), diag::note_previous_definition); 05181 05182 // Try to recover by implicitly importing this module. 05183 createImplicitModuleImportForErrorRecovery(Loc, Owner); 05184 } 05185 05186 // We lock in the inheritance model once somebody has asked us to ensure 05187 // that a pointer-to-member type is complete. 05188 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 05189 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 05190 if (!MPTy->getClass()->isDependentType()) { 05191 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0); 05192 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 05193 } 05194 } 05195 } 05196 05197 return false; 05198 } 05199 05200 const TagType *Tag = T->getAs<TagType>(); 05201 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 05202 05203 // If there's an unimported definition of this type in a module (for 05204 // instance, because we forward declared it, then imported the definition), 05205 // import that definition now. 05206 // 05207 // FIXME: What about other cases where an import extends a redeclaration 05208 // chain for a declaration that can be accessed through a mechanism other 05209 // than name lookup (eg, referenced in a template, or a variable whose type 05210 // could be completed by the module)? 05211 if (Tag || IFace) { 05212 NamedDecl *D = 05213 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 05214 05215 // Avoid diagnosing invalid decls as incomplete. 05216 if (D->isInvalidDecl()) 05217 return true; 05218 05219 // Give the external AST source a chance to complete the type. 05220 if (auto *Source = Context.getExternalSource()) { 05221 if (Tag) 05222 Source->CompleteType(Tag->getDecl()); 05223 else 05224 Source->CompleteType(IFace->getDecl()); 05225 05226 // If the external source completed the type, go through the motions 05227 // again to ensure we're allowed to use the completed type. 05228 if (!T->isIncompleteType()) 05229 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 05230 } 05231 } 05232 05233 // If we have a class template specialization or a class member of a 05234 // class template specialization, or an array with known size of such, 05235 // try to instantiate it. 05236 QualType MaybeTemplate = T; 05237 while (const ConstantArrayType *Array 05238 = Context.getAsConstantArrayType(MaybeTemplate)) 05239 MaybeTemplate = Array->getElementType(); 05240 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 05241 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 05242 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 05243 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 05244 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 05245 TSK_ImplicitInstantiation, 05246 /*Complain=*/!Diagnoser.Suppressed); 05247 } else if (CXXRecordDecl *Rec 05248 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 05249 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 05250 if (!Rec->isBeingDefined() && Pattern) { 05251 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 05252 assert(MSI && "Missing member specialization information?"); 05253 // This record was instantiated from a class within a template. 05254 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 05255 return InstantiateClass(Loc, Rec, Pattern, 05256 getTemplateInstantiationArgs(Rec), 05257 TSK_ImplicitInstantiation, 05258 /*Complain=*/!Diagnoser.Suppressed); 05259 } 05260 } 05261 } 05262 05263 if (Diagnoser.Suppressed) 05264 return true; 05265 05266 // We have an incomplete type. Produce a diagnostic. 05267 if (Ident___float128 && 05268 T == Context.getTypeDeclType(Context.getFloat128StubType())) { 05269 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128); 05270 return true; 05271 } 05272 05273 Diagnoser.diagnose(*this, Loc, T); 05274 05275 // If the type was a forward declaration of a class/struct/union 05276 // type, produce a note. 05277 if (Tag && !Tag->getDecl()->isInvalidDecl()) 05278 Diag(Tag->getDecl()->getLocation(), 05279 Tag->isBeingDefined() ? diag::note_type_being_defined 05280 : diag::note_forward_declaration) 05281 << QualType(Tag, 0); 05282 05283 // If the Objective-C class was a forward declaration, produce a note. 05284 if (IFace && !IFace->getDecl()->isInvalidDecl()) 05285 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 05286 05287 // If we have external information that we can use to suggest a fix, 05288 // produce a note. 05289 if (ExternalSource) 05290 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 05291 05292 return true; 05293 } 05294 05295 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 05296 unsigned DiagID) { 05297 TypeDiagnoserDiag Diagnoser(DiagID); 05298 return RequireCompleteType(Loc, T, Diagnoser); 05299 } 05300 05301 /// \brief Get diagnostic %select index for tag kind for 05302 /// literal type diagnostic message. 05303 /// WARNING: Indexes apply to particular diagnostics only! 05304 /// 05305 /// \returns diagnostic %select index. 05306 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 05307 switch (Tag) { 05308 case TTK_Struct: return 0; 05309 case TTK_Interface: return 1; 05310 case TTK_Class: return 2; 05311 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 05312 } 05313 } 05314 05315 /// @brief Ensure that the type T is a literal type. 05316 /// 05317 /// This routine checks whether the type @p T is a literal type. If @p T is an 05318 /// incomplete type, an attempt is made to complete it. If @p T is a literal 05319 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 05320 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 05321 /// it the type @p T), along with notes explaining why the type is not a 05322 /// literal type, and returns true. 05323 /// 05324 /// @param Loc The location in the source that the non-literal type 05325 /// diagnostic should refer to. 05326 /// 05327 /// @param T The type that this routine is examining for literalness. 05328 /// 05329 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 05330 /// 05331 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 05332 /// @c false otherwise. 05333 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 05334 TypeDiagnoser &Diagnoser) { 05335 assert(!T->isDependentType() && "type should not be dependent"); 05336 05337 QualType ElemType = Context.getBaseElementType(T); 05338 RequireCompleteType(Loc, ElemType, 0); 05339 05340 if (T->isLiteralType(Context)) 05341 return false; 05342 05343 if (Diagnoser.Suppressed) 05344 return true; 05345 05346 Diagnoser.diagnose(*this, Loc, T); 05347 05348 if (T->isVariableArrayType()) 05349 return true; 05350 05351 const RecordType *RT = ElemType->getAs<RecordType>(); 05352 if (!RT) 05353 return true; 05354 05355 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 05356 05357 // A partially-defined class type can't be a literal type, because a literal 05358 // class type must have a trivial destructor (which can't be checked until 05359 // the class definition is complete). 05360 if (!RD->isCompleteDefinition()) { 05361 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T); 05362 return true; 05363 } 05364 05365 // If the class has virtual base classes, then it's not an aggregate, and 05366 // cannot have any constexpr constructors or a trivial default constructor, 05367 // so is non-literal. This is better to diagnose than the resulting absence 05368 // of constexpr constructors. 05369 if (RD->getNumVBases()) { 05370 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 05371 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 05372 for (const auto &I : RD->vbases()) 05373 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 05374 << I.getSourceRange(); 05375 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 05376 !RD->hasTrivialDefaultConstructor()) { 05377 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 05378 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 05379 for (const auto &I : RD->bases()) { 05380 if (!I.getType()->isLiteralType(Context)) { 05381 Diag(I.getLocStart(), 05382 diag::note_non_literal_base_class) 05383 << RD << I.getType() << I.getSourceRange(); 05384 return true; 05385 } 05386 } 05387 for (const auto *I : RD->fields()) { 05388 if (!I->getType()->isLiteralType(Context) || 05389 I->getType().isVolatileQualified()) { 05390 Diag(I->getLocation(), diag::note_non_literal_field) 05391 << RD << I << I->getType() 05392 << I->getType().isVolatileQualified(); 05393 return true; 05394 } 05395 } 05396 } else if (!RD->hasTrivialDestructor()) { 05397 // All fields and bases are of literal types, so have trivial destructors. 05398 // If this class's destructor is non-trivial it must be user-declared. 05399 CXXDestructorDecl *Dtor = RD->getDestructor(); 05400 assert(Dtor && "class has literal fields and bases but no dtor?"); 05401 if (!Dtor) 05402 return true; 05403 05404 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 05405 diag::note_non_literal_user_provided_dtor : 05406 diag::note_non_literal_nontrivial_dtor) << RD; 05407 if (!Dtor->isUserProvided()) 05408 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 05409 } 05410 05411 return true; 05412 } 05413 05414 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 05415 TypeDiagnoserDiag Diagnoser(DiagID); 05416 return RequireLiteralType(Loc, T, Diagnoser); 05417 } 05418 05419 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 05420 /// and qualified by the nested-name-specifier contained in SS. 05421 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 05422 const CXXScopeSpec &SS, QualType T) { 05423 if (T.isNull()) 05424 return T; 05425 NestedNameSpecifier *NNS; 05426 if (SS.isValid()) 05427 NNS = SS.getScopeRep(); 05428 else { 05429 if (Keyword == ETK_None) 05430 return T; 05431 NNS = nullptr; 05432 } 05433 return Context.getElaboratedType(Keyword, NNS, T); 05434 } 05435 05436 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 05437 ExprResult ER = CheckPlaceholderExpr(E); 05438 if (ER.isInvalid()) return QualType(); 05439 E = ER.get(); 05440 05441 if (!E->isTypeDependent()) { 05442 QualType T = E->getType(); 05443 if (const TagType *TT = T->getAs<TagType>()) 05444 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 05445 } 05446 return Context.getTypeOfExprType(E); 05447 } 05448 05449 /// getDecltypeForExpr - Given an expr, will return the decltype for 05450 /// that expression, according to the rules in C++11 05451 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 05452 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 05453 if (E->isTypeDependent()) 05454 return S.Context.DependentTy; 05455 05456 // C++11 [dcl.type.simple]p4: 05457 // The type denoted by decltype(e) is defined as follows: 05458 // 05459 // - if e is an unparenthesized id-expression or an unparenthesized class 05460 // member access (5.2.5), decltype(e) is the type of the entity named 05461 // by e. If there is no such entity, or if e names a set of overloaded 05462 // functions, the program is ill-formed; 05463 // 05464 // We apply the same rules for Objective-C ivar and property references. 05465 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 05466 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 05467 return VD->getType(); 05468 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 05469 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 05470 return FD->getType(); 05471 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 05472 return IR->getDecl()->getType(); 05473 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 05474 if (PR->isExplicitProperty()) 05475 return PR->getExplicitProperty()->getType(); 05476 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 05477 return PE->getType(); 05478 } 05479 05480 // C++11 [expr.lambda.prim]p18: 05481 // Every occurrence of decltype((x)) where x is a possibly 05482 // parenthesized id-expression that names an entity of automatic 05483 // storage duration is treated as if x were transformed into an 05484 // access to a corresponding data member of the closure type that 05485 // would have been declared if x were an odr-use of the denoted 05486 // entity. 05487 using namespace sema; 05488 if (S.getCurLambda()) { 05489 if (isa<ParenExpr>(E)) { 05490 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 05491 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 05492 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 05493 if (!T.isNull()) 05494 return S.Context.getLValueReferenceType(T); 05495 } 05496 } 05497 } 05498 } 05499 05500 05501 // C++11 [dcl.type.simple]p4: 05502 // [...] 05503 QualType T = E->getType(); 05504 switch (E->getValueKind()) { 05505 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 05506 // type of e; 05507 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 05508 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 05509 // type of e; 05510 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 05511 // - otherwise, decltype(e) is the type of e. 05512 case VK_RValue: break; 05513 } 05514 05515 return T; 05516 } 05517 05518 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 05519 ExprResult ER = CheckPlaceholderExpr(E); 05520 if (ER.isInvalid()) return QualType(); 05521 E = ER.get(); 05522 05523 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 05524 } 05525 05526 QualType Sema::BuildUnaryTransformType(QualType BaseType, 05527 UnaryTransformType::UTTKind UKind, 05528 SourceLocation Loc) { 05529 switch (UKind) { 05530 case UnaryTransformType::EnumUnderlyingType: 05531 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 05532 Diag(Loc, diag::err_only_enums_have_underlying_types); 05533 return QualType(); 05534 } else { 05535 QualType Underlying = BaseType; 05536 if (!BaseType->isDependentType()) { 05537 // The enum could be incomplete if we're parsing its definition or 05538 // recovering from an error. 05539 NamedDecl *FwdDecl = nullptr; 05540 if (BaseType->isIncompleteType(&FwdDecl)) { 05541 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 05542 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 05543 return QualType(); 05544 } 05545 05546 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 05547 assert(ED && "EnumType has no EnumDecl"); 05548 05549 DiagnoseUseOfDecl(ED, Loc); 05550 05551 Underlying = ED->getIntegerType(); 05552 assert(!Underlying.isNull()); 05553 } 05554 return Context.getUnaryTransformType(BaseType, Underlying, 05555 UnaryTransformType::EnumUnderlyingType); 05556 } 05557 } 05558 llvm_unreachable("unknown unary transform type"); 05559 } 05560 05561 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 05562 if (!T->isDependentType()) { 05563 // FIXME: It isn't entirely clear whether incomplete atomic types 05564 // are allowed or not; for simplicity, ban them for the moment. 05565 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 05566 return QualType(); 05567 05568 int DisallowedKind = -1; 05569 if (T->isArrayType()) 05570 DisallowedKind = 1; 05571 else if (T->isFunctionType()) 05572 DisallowedKind = 2; 05573 else if (T->isReferenceType()) 05574 DisallowedKind = 3; 05575 else if (T->isAtomicType()) 05576 DisallowedKind = 4; 05577 else if (T.hasQualifiers()) 05578 DisallowedKind = 5; 05579 else if (!T.isTriviallyCopyableType(Context)) 05580 // Some other non-trivially-copyable type (probably a C++ class) 05581 DisallowedKind = 6; 05582 05583 if (DisallowedKind != -1) { 05584 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 05585 return QualType(); 05586 } 05587 05588 // FIXME: Do we need any handling for ARC here? 05589 } 05590 05591 // Build the pointer type. 05592 return Context.getAtomicType(T); 05593 }