Sema.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  1. //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the actions class which performs semantic analysis and
  11. // builds an AST out of a parse stream.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/SemaInternal.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTDiagnostic.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclFriend.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/StmtCXX.h"
  23. #include "clang/Basic/DiagnosticOptions.h"
  24. #include "clang/Basic/FileManager.h"
  25. #include "clang/Basic/PartialDiagnostic.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/Lex/HeaderSearch.h"
  28. #include "clang/Lex/Preprocessor.h"
  29. #include "clang/Sema/CXXFieldCollector.h"
  30. #include "clang/Sema/DelayedDiagnostic.h"
  31. #include "clang/Sema/ExternalSemaSource.h"
  32. #include "clang/Sema/MultiplexExternalSemaSource.h"
  33. #include "clang/Sema/ObjCMethodList.h"
  34. #include "clang/Sema/PrettyDeclStackTrace.h"
  35. #include "clang/Sema/Scope.h"
  36. #include "clang/Sema/ScopeInfo.h"
  37. #include "clang/Sema/SemaConsumer.h"
  38. #include "clang/Sema/TemplateDeduction.h"
  39. #include "llvm/ADT/APFloat.h"
  40. #include "llvm/ADT/DenseMap.h"
  41. #include "llvm/ADT/SmallSet.h"
  42. #include "llvm/Support/CrashRecoveryContext.h"
  43. using namespace clang;
  44. using namespace sema;
  45. SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
  46. return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
  47. }
  48. ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
  49. PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
  50. const Preprocessor &PP) {
  51. PrintingPolicy Policy = Context.getPrintingPolicy();
  52. Policy.Bool = Context.getLangOpts().Bool;
  53. if (!Policy.Bool) {
  54. if (const MacroInfo *
  55. BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
  56. Policy.Bool = BoolMacro->isObjectLike() &&
  57. BoolMacro->getNumTokens() == 1 &&
  58. BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
  59. }
  60. }
  61. return Policy;
  62. }
  63. void Sema::ActOnTranslationUnitScope(Scope *S) {
  64. TUScope = S;
  65. PushDeclContext(S, Context.getTranslationUnitDecl());
  66. }
  67. Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
  68. TranslationUnitKind TUKind,
  69. CodeCompleteConsumer *CodeCompleter)
  70. : ExternalSource(nullptr),
  71. isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
  72. LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
  73. Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
  74. CollectStats(false), CodeCompleter(CodeCompleter),
  75. CurContext(nullptr), OriginalLexicalContext(nullptr),
  76. PackContext(nullptr), MSStructPragmaOn(false),
  77. MSPointerToMemberRepresentationMethod(
  78. LangOpts.getMSPointerToMemberRepresentationMethod()),
  79. VtorDispModeStack(1, MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
  80. DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
  81. CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
  82. IsBuildingRecoveryCallExpr(false),
  83. ExprNeedsCleanups(false), LateTemplateParser(nullptr),
  84. LateTemplateParserCleanup(nullptr),
  85. OpaqueParser(nullptr), IdResolver(pp), StdInitializerList(nullptr),
  86. CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
  87. NSNumberDecl(nullptr), NSValueDecl(nullptr),
  88. NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
  89. ValueWithBytesObjCTypeMethod(nullptr),
  90. NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
  91. NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
  92. MSAsmLabelNameCounter(0),
  93. GlobalNewDeleteDeclared(false),
  94. TUKind(TUKind),
  95. NumSFINAEErrors(0),
  96. CachedFakeTopLevelModule(nullptr),
  97. AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
  98. NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
  99. CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
  100. TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
  101. VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
  102. Ident_super(nullptr), Ident___float128(nullptr)
  103. {
  104. TUScope = nullptr;
  105. LoadedExternalKnownNamespaces = false;
  106. #if 0 // HLSL Change Starts
  107. for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
  108. NSNumberLiteralMethods[I] = nullptr;
  109. if (getLangOpts().ObjC1)
  110. NSAPIObj.reset(new NSAPI(Context));
  111. #endif // HLSL Change Ends
  112. if (getLangOpts().CPlusPlus)
  113. FieldCollector.reset(new CXXFieldCollector());
  114. // Tell diagnostics how to render things from the AST library.
  115. PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
  116. &Context);
  117. ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, false, nullptr, false);
  118. FunctionScopes.push_back(new FunctionScopeInfo(Diags));
  119. // Initilization of data sharing attributes stack for OpenMP
  120. // InitDataSharingAttributesStack(); // HLSL Change - no support for OpenMP
  121. }
  122. void Sema::addImplicitTypedef(StringRef Name, QualType T) {
  123. DeclarationName DN = &Context.Idents.get(Name);
  124. if (IdResolver.begin(DN) == IdResolver.end())
  125. PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
  126. }
  127. void Sema::Initialize() {
  128. // Tell the AST consumer about this Sema object.
  129. Consumer.Initialize(Context);
  130. // FIXME: Isn't this redundant with the initialization above?
  131. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  132. SC->InitializeSema(*this);
  133. // Tell the external Sema source about this Sema object.
  134. if (ExternalSemaSource *ExternalSema
  135. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  136. ExternalSema->InitializeSema(*this);
  137. // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
  138. // will not be able to merge any duplicate __va_list_tag decls correctly.
  139. VAListTagName = PP.getIdentifierInfo("__va_list_tag");
  140. // Initialize predefined 128-bit integer types, if needed.
  141. if (Context.getTargetInfo().hasInt128Type()) {
  142. // If either of the 128-bit integer types are unavailable to name lookup,
  143. // define them now.
  144. DeclarationName Int128 = &Context.Idents.get("__int128_t");
  145. if (IdResolver.begin(Int128) == IdResolver.end())
  146. PushOnScopeChains(Context.getInt128Decl(), TUScope);
  147. DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
  148. if (IdResolver.begin(UInt128) == IdResolver.end())
  149. PushOnScopeChains(Context.getUInt128Decl(), TUScope);
  150. }
  151. // Initialize predefined Objective-C types:
  152. if (PP.getLangOpts().ObjC1) {
  153. // If 'SEL' does not yet refer to any declarations, make it refer to the
  154. // predefined 'SEL'.
  155. DeclarationName SEL = &Context.Idents.get("SEL");
  156. if (IdResolver.begin(SEL) == IdResolver.end())
  157. PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
  158. // If 'id' does not yet refer to any declarations, make it refer to the
  159. // predefined 'id'.
  160. DeclarationName Id = &Context.Idents.get("id");
  161. if (IdResolver.begin(Id) == IdResolver.end())
  162. PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
  163. // Create the built-in typedef for 'Class'.
  164. DeclarationName Class = &Context.Idents.get("Class");
  165. if (IdResolver.begin(Class) == IdResolver.end())
  166. PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
  167. // Create the built-in forward declaratino for 'Protocol'.
  168. DeclarationName Protocol = &Context.Idents.get("Protocol");
  169. if (IdResolver.begin(Protocol) == IdResolver.end())
  170. PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
  171. }
  172. // Initialize Microsoft "predefined C++ types".
  173. if (PP.getLangOpts().MSVCCompat) {
  174. if (PP.getLangOpts().CPlusPlus &&
  175. IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
  176. PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
  177. TUScope);
  178. addImplicitTypedef("size_t", Context.getSizeType());
  179. }
  180. // Initialize predefined OpenCL types.
  181. if (PP.getLangOpts().OpenCL) {
  182. addImplicitTypedef("image1d_t", Context.OCLImage1dTy);
  183. addImplicitTypedef("image1d_array_t", Context.OCLImage1dArrayTy);
  184. addImplicitTypedef("image1d_buffer_t", Context.OCLImage1dBufferTy);
  185. addImplicitTypedef("image2d_t", Context.OCLImage2dTy);
  186. addImplicitTypedef("image2d_array_t", Context.OCLImage2dArrayTy);
  187. addImplicitTypedef("image3d_t", Context.OCLImage3dTy);
  188. addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
  189. addImplicitTypedef("event_t", Context.OCLEventTy);
  190. if (getLangOpts().OpenCLVersion >= 200) {
  191. addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
  192. addImplicitTypedef("atomic_uint",
  193. Context.getAtomicType(Context.UnsignedIntTy));
  194. addImplicitTypedef("atomic_long", Context.getAtomicType(Context.LongTy));
  195. addImplicitTypedef("atomic_ulong",
  196. Context.getAtomicType(Context.UnsignedLongTy));
  197. addImplicitTypedef("atomic_float",
  198. Context.getAtomicType(Context.FloatTy));
  199. addImplicitTypedef("atomic_double",
  200. Context.getAtomicType(Context.DoubleTy));
  201. // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
  202. // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
  203. addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
  204. addImplicitTypedef("atomic_intptr_t",
  205. Context.getAtomicType(Context.getIntPtrType()));
  206. addImplicitTypedef("atomic_uintptr_t",
  207. Context.getAtomicType(Context.getUIntPtrType()));
  208. addImplicitTypedef("atomic_size_t",
  209. Context.getAtomicType(Context.getSizeType()));
  210. addImplicitTypedef("atomic_ptrdiff_t",
  211. Context.getAtomicType(Context.getPointerDiffType()));
  212. }
  213. }
  214. DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
  215. if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
  216. PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
  217. }
  218. Sema::~Sema() {
  219. llvm::DeleteContainerSeconds(LateParsedTemplateMap);
  220. if (PackContext) FreePackedContext();
  221. if (VisContext) FreeVisContext();
  222. // Kill all the active scopes.
  223. for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
  224. delete FunctionScopes[I];
  225. if (FunctionScopes.size() == 1)
  226. delete FunctionScopes[0];
  227. // Tell the SemaConsumer to forget about us; we're going out of scope.
  228. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  229. SC->ForgetSema();
  230. // Detach from the external Sema source.
  231. if (ExternalSemaSource *ExternalSema
  232. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  233. ExternalSema->ForgetSema();
  234. // If Sema's ExternalSource is the multiplexer - we own it.
  235. if (isMultiplexExternalSource)
  236. delete ExternalSource;
  237. threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
  238. // Destroys data sharing attributes stack for OpenMP
  239. // DestroyDataSharingAttributesStack(); // HLSL Change - no support for OpenMP
  240. assert(DelayedTypos.empty() && "Uncorrected typos!");
  241. }
  242. /// makeUnavailableInSystemHeader - There is an error in the current
  243. /// context. If we're still in a system header, and we can plausibly
  244. /// make the relevant declaration unavailable instead of erroring, do
  245. /// so and return true.
  246. bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
  247. StringRef msg) {
  248. // If we're not in a function, it's an error.
  249. FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
  250. if (!fn) return false;
  251. // If we're in template instantiation, it's an error.
  252. if (!ActiveTemplateInstantiations.empty())
  253. return false;
  254. // If that function's not in a system header, it's an error.
  255. if (!Context.getSourceManager().isInSystemHeader(loc))
  256. return false;
  257. // If the function is already unavailable, it's not an error.
  258. if (fn->hasAttr<UnavailableAttr>()) return true;
  259. fn->addAttr(UnavailableAttr::CreateImplicit(Context, msg, loc));
  260. return true;
  261. }
  262. ASTMutationListener *Sema::getASTMutationListener() const {
  263. return getASTConsumer().GetASTMutationListener();
  264. }
  265. ///\brief Registers an external source. If an external source already exists,
  266. /// creates a multiplex external source and appends to it.
  267. ///
  268. ///\param[in] E - A non-null external sema source.
  269. ///
  270. void Sema::addExternalSource(ExternalSemaSource *E) {
  271. assert(E && "Cannot use with NULL ptr");
  272. if (!ExternalSource) {
  273. ExternalSource = E;
  274. return;
  275. }
  276. if (isMultiplexExternalSource)
  277. static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
  278. else {
  279. ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
  280. isMultiplexExternalSource = true;
  281. }
  282. }
  283. /// \brief Print out statistics about the semantic analysis.
  284. void Sema::PrintStats() const {
  285. llvm::errs() << "\n*** Semantic Analysis Stats:\n";
  286. llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
  287. BumpAlloc.PrintStats();
  288. AnalysisWarnings.PrintStats();
  289. }
  290. /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
  291. /// If there is already an implicit cast, merge into the existing one.
  292. /// The result is of the given category.
  293. ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
  294. CastKind Kind, ExprValueKind VK,
  295. const CXXCastPath *BasePath,
  296. CheckedConversionKind CCK) {
  297. #ifndef NDEBUG
  298. if (VK == VK_RValue && !E->isRValue()) {
  299. switch (Kind) {
  300. default:
  301. llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
  302. "kind");
  303. case CK_LValueToRValue:
  304. case CK_ArrayToPointerDecay:
  305. case CK_FunctionToPointerDecay:
  306. case CK_ToVoid:
  307. break;
  308. }
  309. }
  310. assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
  311. #endif
  312. if (VK == VK_LValue) {
  313. if (Kind == CastKind::CK_HLSLVectorTruncationCast ||
  314. Kind == CastKind::CK_HLSLMatrixTruncationCast) {
  315. Diag(E->getLocStart(), diag::err_hlsl_unsupported_lvalue_cast_op);
  316. }
  317. }
  318. // Check whether we're implicitly casting from a nullable type to a nonnull
  319. // type.
  320. if (auto exprNullability = E->getType()->getNullability(Context)) {
  321. if (*exprNullability == NullabilityKind::Nullable) {
  322. if (auto typeNullability = Ty->getNullability(Context)) {
  323. if (*typeNullability == NullabilityKind::NonNull) {
  324. Diag(E->getLocStart(), diag::warn_nullability_lost)
  325. << E->getType() << Ty;
  326. }
  327. }
  328. }
  329. }
  330. QualType ExprTy = Context.getCanonicalType(E->getType());
  331. QualType TypeTy = Context.getCanonicalType(Ty);
  332. if (ExprTy == TypeTy)
  333. return E;
  334. if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  335. if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
  336. ImpCast->setType(Ty);
  337. ImpCast->setValueKind(VK);
  338. return E;
  339. }
  340. }
  341. return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
  342. }
  343. /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
  344. /// to the conversion from scalar type ScalarTy to the Boolean type.
  345. CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
  346. switch (ScalarTy->getScalarTypeKind()) {
  347. case Type::STK_Bool: return CK_NoOp;
  348. case Type::STK_CPointer: return CK_PointerToBoolean;
  349. case Type::STK_BlockPointer: return CK_PointerToBoolean;
  350. case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
  351. case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
  352. case Type::STK_Integral: return CK_IntegralToBoolean;
  353. case Type::STK_Floating: return CK_FloatingToBoolean;
  354. case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
  355. case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
  356. }
  357. return CK_Invalid;
  358. }
  359. /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
  360. static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
  361. if (D->getMostRecentDecl()->isUsed())
  362. return true;
  363. if (D->isExternallyVisible())
  364. return true;
  365. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  366. // UnusedFileScopedDecls stores the first declaration.
  367. // The declaration may have become definition so check again.
  368. const FunctionDecl *DeclToCheck;
  369. if (FD->hasBody(DeclToCheck))
  370. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  371. // Later redecls may add new information resulting in not having to warn,
  372. // so check again.
  373. DeclToCheck = FD->getMostRecentDecl();
  374. if (DeclToCheck != FD)
  375. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  376. }
  377. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  378. // If a variable usable in constant expressions is referenced,
  379. // don't warn if it isn't used: if the value of a variable is required
  380. // for the computation of a constant expression, it doesn't make sense to
  381. // warn even if the variable isn't odr-used. (isReferenced doesn't
  382. // precisely reflect that, but it's a decent approximation.)
  383. if (VD->isReferenced() &&
  384. VD->isUsableInConstantExpressions(SemaRef->Context))
  385. return true;
  386. // UnusedFileScopedDecls stores the first declaration.
  387. // The declaration may have become definition so check again.
  388. const VarDecl *DeclToCheck = VD->getDefinition();
  389. if (DeclToCheck)
  390. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  391. // Later redecls may add new information resulting in not having to warn,
  392. // so check again.
  393. DeclToCheck = VD->getMostRecentDecl();
  394. if (DeclToCheck != VD)
  395. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  396. }
  397. return false;
  398. }
  399. /// Obtains a sorted list of functions that are undefined but ODR-used.
  400. void Sema::getUndefinedButUsed(
  401. SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
  402. for (llvm::DenseMap<NamedDecl *, SourceLocation>::iterator
  403. I = UndefinedButUsed.begin(), E = UndefinedButUsed.end();
  404. I != E; ++I) {
  405. NamedDecl *ND = I->first;
  406. // Ignore attributes that have become invalid.
  407. if (ND->isInvalidDecl()) continue;
  408. // __attribute__((weakref)) is basically a definition.
  409. if (ND->hasAttr<WeakRefAttr>()) continue;
  410. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  411. if (FD->isDefined())
  412. continue;
  413. if (FD->isExternallyVisible() &&
  414. !FD->getMostRecentDecl()->isInlined())
  415. continue;
  416. } else {
  417. if (cast<VarDecl>(ND)->hasDefinition() != VarDecl::DeclarationOnly)
  418. continue;
  419. if (ND->isExternallyVisible())
  420. continue;
  421. }
  422. Undefined.push_back(std::make_pair(ND, I->second));
  423. }
  424. // Sort (in order of use site) so that we're not dependent on the iteration
  425. // order through an llvm::DenseMap.
  426. SourceManager &SM = Context.getSourceManager();
  427. std::sort(Undefined.begin(), Undefined.end(),
  428. [&SM](const std::pair<NamedDecl *, SourceLocation> &l,
  429. const std::pair<NamedDecl *, SourceLocation> &r) {
  430. if (l.second.isValid() && !r.second.isValid())
  431. return true;
  432. if (!l.second.isValid() && r.second.isValid())
  433. return false;
  434. if (l.second != r.second)
  435. return SM.isBeforeInTranslationUnit(l.second, r.second);
  436. return SM.isBeforeInTranslationUnit(l.first->getLocation(),
  437. r.first->getLocation());
  438. });
  439. }
  440. /// checkUndefinedButUsed - Check for undefined objects with internal linkage
  441. /// or that are inline.
  442. static void checkUndefinedButUsed(Sema &S) {
  443. if (S.UndefinedButUsed.empty()) return;
  444. // Collect all the still-undefined entities with internal linkage.
  445. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  446. S.getUndefinedButUsed(Undefined);
  447. if (Undefined.empty()) return;
  448. for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
  449. I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
  450. NamedDecl *ND = I->first;
  451. if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
  452. // An exported function will always be emitted when defined, so even if
  453. // the function is inline, it doesn't have to be emitted in this TU. An
  454. // imported function implies that it has been exported somewhere else.
  455. continue;
  456. }
  457. if (!ND->isExternallyVisible()) {
  458. S.Diag(ND->getLocation(), diag::warn_undefined_internal)
  459. << isa<VarDecl>(ND) << ND;
  460. } else {
  461. assert(cast<FunctionDecl>(ND)->getMostRecentDecl()->isInlined() &&
  462. "used object requires definition but isn't inline or internal?");
  463. S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
  464. }
  465. if (I->second.isValid())
  466. S.Diag(I->second, diag::note_used_here);
  467. }
  468. }
  469. void Sema::LoadExternalWeakUndeclaredIdentifiers() {
  470. if (!ExternalSource)
  471. return;
  472. SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
  473. ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
  474. for (auto &WeakID : WeakIDs)
  475. WeakUndeclaredIdentifiers.insert(WeakID);
  476. }
  477. typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
  478. /// \brief Returns true, if all methods and nested classes of the given
  479. /// CXXRecordDecl are defined in this translation unit.
  480. ///
  481. /// Should only be called from ActOnEndOfTranslationUnit so that all
  482. /// definitions are actually read.
  483. static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
  484. RecordCompleteMap &MNCComplete) {
  485. RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
  486. if (Cache != MNCComplete.end())
  487. return Cache->second;
  488. if (!RD->isCompleteDefinition())
  489. return false;
  490. bool Complete = true;
  491. for (DeclContext::decl_iterator I = RD->decls_begin(),
  492. E = RD->decls_end();
  493. I != E && Complete; ++I) {
  494. if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
  495. Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
  496. else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
  497. // If the template function is marked as late template parsed at this
  498. // point, it has not been instantiated and therefore we have not
  499. // performed semantic analysis on it yet, so we cannot know if the type
  500. // can be considered complete.
  501. Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
  502. F->getTemplatedDecl()->isDefined();
  503. else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
  504. if (R->isInjectedClassName())
  505. continue;
  506. if (R->hasDefinition())
  507. Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
  508. MNCComplete);
  509. else
  510. Complete = false;
  511. }
  512. }
  513. MNCComplete[RD] = Complete;
  514. return Complete;
  515. }
  516. /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
  517. /// translation unit, i.e. all methods are defined or pure virtual and all
  518. /// friends, friend functions and nested classes are fully defined in this
  519. /// translation unit.
  520. ///
  521. /// Should only be called from ActOnEndOfTranslationUnit so that all
  522. /// definitions are actually read.
  523. static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
  524. RecordCompleteMap &RecordsComplete,
  525. RecordCompleteMap &MNCComplete) {
  526. RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
  527. if (Cache != RecordsComplete.end())
  528. return Cache->second;
  529. bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
  530. for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
  531. E = RD->friend_end();
  532. I != E && Complete; ++I) {
  533. // Check if friend classes and methods are complete.
  534. if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
  535. // Friend classes are available as the TypeSourceInfo of the FriendDecl.
  536. if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
  537. Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
  538. else
  539. Complete = false;
  540. } else {
  541. // Friend functions are available through the NamedDecl of FriendDecl.
  542. if (const FunctionDecl *FD =
  543. dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
  544. Complete = FD->isDefined();
  545. else
  546. // This is a template friend, give up.
  547. Complete = false;
  548. }
  549. }
  550. RecordsComplete[RD] = Complete;
  551. return Complete;
  552. }
  553. void Sema::emitAndClearUnusedLocalTypedefWarnings() {
  554. if (ExternalSource)
  555. ExternalSource->ReadUnusedLocalTypedefNameCandidates(
  556. UnusedLocalTypedefNameCandidates);
  557. for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
  558. if (TD->isReferenced())
  559. continue;
  560. Diag(TD->getLocation(), diag::warn_unused_local_typedef)
  561. << isa<TypeAliasDecl>(TD) << TD->getDeclName();
  562. }
  563. UnusedLocalTypedefNameCandidates.clear();
  564. }
  565. /// ActOnEndOfTranslationUnit - This is called at the very end of the
  566. /// translation unit when EOF is reached and all but the top-level scope is
  567. /// popped.
  568. void Sema::ActOnEndOfTranslationUnit() {
  569. assert(DelayedDiagnostics.getCurrentPool() == nullptr
  570. && "reached end of translation unit with a pool attached?");
  571. // If code completion is enabled, don't perform any end-of-translation-unit
  572. // work.
  573. if (PP.isCodeCompletionEnabled())
  574. return;
  575. // Complete translation units and modules define vtables and perform implicit
  576. // instantiations. PCH files do not.
  577. if (TUKind != TU_Prefix) {
  578. DiagnoseUseOfUnimplementedSelectors();
  579. // If DefinedUsedVTables ends up marking any virtual member functions it
  580. // might lead to more pending template instantiations, which we then need
  581. // to instantiate.
  582. DefineUsedVTables();
  583. // C++: Perform implicit template instantiations.
  584. //
  585. // FIXME: When we perform these implicit instantiations, we do not
  586. // carefully keep track of the point of instantiation (C++ [temp.point]).
  587. // This means that name lookup that occurs within the template
  588. // instantiation will always happen at the end of the translation unit,
  589. // so it will find some names that are not required to be found. This is
  590. // valid, but we could do better by diagnosing if an instantiation uses a
  591. // name that was not visible at its first point of instantiation.
  592. if (ExternalSource) {
  593. // Load pending instantiations from the external source.
  594. SmallVector<PendingImplicitInstantiation, 4> Pending;
  595. ExternalSource->ReadPendingInstantiations(Pending);
  596. PendingInstantiations.insert(PendingInstantiations.begin(),
  597. Pending.begin(), Pending.end());
  598. }
  599. PerformPendingInstantiations();
  600. if (LateTemplateParserCleanup)
  601. LateTemplateParserCleanup(OpaqueParser);
  602. CheckDelayedMemberExceptionSpecs();
  603. }
  604. // All delayed member exception specs should be checked or we end up accepting
  605. // incompatible declarations.
  606. // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
  607. // write out the lists to the AST file (if any).
  608. assert(DelayedDefaultedMemberExceptionSpecs.empty());
  609. assert(DelayedExceptionSpecChecks.empty());
  610. // Remove file scoped decls that turned out to be used.
  611. UnusedFileScopedDecls.erase(
  612. std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
  613. UnusedFileScopedDecls.end(),
  614. [this](const DeclaratorDecl *DD) {
  615. return ShouldRemoveFromUnused(this, DD);
  616. }),
  617. UnusedFileScopedDecls.end());
  618. if (TUKind == TU_Prefix) {
  619. // Translation unit prefixes don't need any of the checking below.
  620. TUScope = nullptr;
  621. return;
  622. }
  623. // Check for #pragma weak identifiers that were never declared
  624. LoadExternalWeakUndeclaredIdentifiers();
  625. for (auto WeakID : WeakUndeclaredIdentifiers) {
  626. if (WeakID.second.getUsed())
  627. continue;
  628. Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
  629. << WeakID.first;
  630. }
  631. if (LangOpts.CPlusPlus11 &&
  632. !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
  633. CheckDelegatingCtorCycles();
  634. if (TUKind == TU_Module) {
  635. // If we are building a module, resolve all of the exported declarations
  636. // now.
  637. if (Module *CurrentModule = PP.getCurrentModule()) {
  638. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  639. SmallVector<Module *, 2> Stack;
  640. Stack.push_back(CurrentModule);
  641. while (!Stack.empty()) {
  642. Module *Mod = Stack.pop_back_val();
  643. // Resolve the exported declarations and conflicts.
  644. // FIXME: Actually complain, once we figure out how to teach the
  645. // diagnostic client to deal with complaints in the module map at this
  646. // point.
  647. ModMap.resolveExports(Mod, /*Complain=*/false);
  648. ModMap.resolveUses(Mod, /*Complain=*/false);
  649. ModMap.resolveConflicts(Mod, /*Complain=*/false);
  650. // Queue the submodules, so their exports will also be resolved.
  651. Stack.append(Mod->submodule_begin(), Mod->submodule_end());
  652. }
  653. }
  654. // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
  655. // modules when they are built, not every time they are used.
  656. emitAndClearUnusedLocalTypedefWarnings();
  657. // Modules don't need any of the checking below.
  658. TUScope = nullptr;
  659. return;
  660. }
  661. // C99 6.9.2p2:
  662. // A declaration of an identifier for an object that has file
  663. // scope without an initializer, and without a storage-class
  664. // specifier or with the storage-class specifier static,
  665. // constitutes a tentative definition. If a translation unit
  666. // contains one or more tentative definitions for an identifier,
  667. // and the translation unit contains no external definition for
  668. // that identifier, then the behavior is exactly as if the
  669. // translation unit contains a file scope declaration of that
  670. // identifier, with the composite type as of the end of the
  671. // translation unit, with an initializer equal to 0.
  672. llvm::SmallSet<VarDecl *, 32> Seen;
  673. for (TentativeDefinitionsType::iterator
  674. T = TentativeDefinitions.begin(ExternalSource),
  675. TEnd = TentativeDefinitions.end();
  676. T != TEnd; ++T)
  677. {
  678. VarDecl *VD = (*T)->getActingDefinition();
  679. // If the tentative definition was completed, getActingDefinition() returns
  680. // null. If we've already seen this variable before, insert()'s second
  681. // return value is false.
  682. if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
  683. continue;
  684. if (const IncompleteArrayType *ArrayT
  685. = Context.getAsIncompleteArrayType(VD->getType())) {
  686. // Set the length of the array to 1 (C99 6.9.2p5).
  687. Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
  688. llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
  689. QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
  690. One, ArrayType::Normal, 0);
  691. VD->setType(T);
  692. } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
  693. diag::err_tentative_def_incomplete_type))
  694. VD->setInvalidDecl();
  695. CheckCompleteVariableDeclaration(VD);
  696. // Notify the consumer that we've completed a tentative definition.
  697. if (!VD->isInvalidDecl())
  698. Consumer.CompleteTentativeDefinition(VD);
  699. }
  700. // If there were errors, disable 'unused' warnings since they will mostly be
  701. // noise.
  702. if (!Diags.hasErrorOccurred()) {
  703. // Output warning for unused file scoped decls.
  704. for (UnusedFileScopedDeclsType::iterator
  705. I = UnusedFileScopedDecls.begin(ExternalSource),
  706. E = UnusedFileScopedDecls.end(); I != E; ++I) {
  707. if (ShouldRemoveFromUnused(this, *I))
  708. continue;
  709. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  710. const FunctionDecl *DiagD;
  711. if (!FD->hasBody(DiagD))
  712. DiagD = FD;
  713. if (DiagD->isDeleted())
  714. continue; // Deleted functions are supposed to be unused.
  715. if (DiagD->isReferenced()) {
  716. if (isa<CXXMethodDecl>(DiagD))
  717. Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
  718. << DiagD->getDeclName();
  719. else {
  720. if (FD->getStorageClass() == SC_Static &&
  721. !FD->isInlineSpecified() &&
  722. !SourceMgr.isInMainFile(
  723. SourceMgr.getExpansionLoc(FD->getLocation())))
  724. Diag(DiagD->getLocation(),
  725. diag::warn_unneeded_static_internal_decl)
  726. << DiagD->getDeclName();
  727. else
  728. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  729. << /*function*/0 << DiagD->getDeclName();
  730. }
  731. } else {
  732. Diag(DiagD->getLocation(),
  733. isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
  734. : diag::warn_unused_function)
  735. << DiagD->getDeclName();
  736. }
  737. } else {
  738. const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
  739. if (!DiagD)
  740. DiagD = cast<VarDecl>(*I);
  741. if (DiagD->isReferenced()) {
  742. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  743. << /*variable*/1 << DiagD->getDeclName();
  744. } else if (DiagD->getType().isConstQualified()) {
  745. Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
  746. << DiagD->getDeclName();
  747. } else {
  748. Diag(DiagD->getLocation(), diag::warn_unused_variable)
  749. << DiagD->getDeclName();
  750. }
  751. }
  752. }
  753. if (ExternalSource)
  754. ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
  755. checkUndefinedButUsed(*this);
  756. emitAndClearUnusedLocalTypedefWarnings();
  757. }
  758. if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
  759. RecordCompleteMap RecordsComplete;
  760. RecordCompleteMap MNCComplete;
  761. for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
  762. E = UnusedPrivateFields.end(); I != E; ++I) {
  763. const NamedDecl *D = *I;
  764. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  765. if (RD && !RD->isUnion() &&
  766. IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
  767. Diag(D->getLocation(), diag::warn_unused_private_field)
  768. << D->getDeclName();
  769. }
  770. }
  771. }
  772. if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
  773. if (ExternalSource)
  774. ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
  775. for (const auto &DeletedFieldInfo : DeleteExprs) {
  776. for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
  777. AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
  778. DeleteExprLoc.second);
  779. }
  780. }
  781. }
  782. // Check we've noticed that we're no longer parsing the initializer for every
  783. // variable. If we miss cases, then at best we have a performance issue and
  784. // at worst a rejects-valid bug.
  785. assert(ParsingInitForAutoVars.empty() &&
  786. "Didn't unmark var as having its initializer parsed");
  787. TUScope = nullptr;
  788. }
  789. //===----------------------------------------------------------------------===//
  790. // Helper functions.
  791. //===----------------------------------------------------------------------===//
  792. DeclContext *Sema::getFunctionLevelDeclContext() {
  793. DeclContext *DC = CurContext;
  794. while (true) {
  795. if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
  796. DC = DC->getParent();
  797. } else if (isa<CXXMethodDecl>(DC) &&
  798. cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
  799. cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
  800. DC = DC->getParent()->getParent();
  801. }
  802. else break;
  803. }
  804. return DC;
  805. }
  806. /// getCurFunctionDecl - If inside of a function body, this returns a pointer
  807. /// to the function decl for the function being parsed. If we're currently
  808. /// in a 'block', this returns the containing context.
  809. FunctionDecl *Sema::getCurFunctionDecl() {
  810. DeclContext *DC = getFunctionLevelDeclContext();
  811. return dyn_cast<FunctionDecl>(DC);
  812. }
  813. ObjCMethodDecl *Sema::getCurMethodDecl() {
  814. DeclContext *DC = getFunctionLevelDeclContext();
  815. while (isa<RecordDecl>(DC))
  816. DC = DC->getParent();
  817. return dyn_cast<ObjCMethodDecl>(DC);
  818. }
  819. NamedDecl *Sema::getCurFunctionOrMethodDecl() {
  820. DeclContext *DC = getFunctionLevelDeclContext();
  821. if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
  822. return cast<NamedDecl>(DC);
  823. return nullptr;
  824. }
  825. void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
  826. // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
  827. // and yet we also use the current diag ID on the DiagnosticsEngine. This has
  828. // been made more painfully obvious by the refactor that introduced this
  829. // function, but it is possible that the incoming argument can be
  830. // eliminnated. If it truly cannot be (for example, there is some reentrancy
  831. // issue I am not seeing yet), then there should at least be a clarifying
  832. // comment somewhere.
  833. if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
  834. switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
  835. Diags.getCurrentDiagID())) {
  836. case DiagnosticIDs::SFINAE_Report:
  837. // We'll report the diagnostic below.
  838. break;
  839. case DiagnosticIDs::SFINAE_SubstitutionFailure:
  840. // Count this failure so that we know that template argument deduction
  841. // has failed.
  842. ++NumSFINAEErrors;
  843. // Make a copy of this suppressed diagnostic and store it with the
  844. // template-deduction information.
  845. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  846. Diagnostic DiagInfo(&Diags);
  847. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  848. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  849. }
  850. Diags.setLastDiagnosticIgnored();
  851. Diags.Clear();
  852. return;
  853. case DiagnosticIDs::SFINAE_AccessControl: {
  854. // Per C++ Core Issue 1170, access control is part of SFINAE.
  855. // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
  856. // make access control a part of SFINAE for the purposes of checking
  857. // type traits.
  858. if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
  859. break;
  860. SourceLocation Loc = Diags.getCurrentDiagLoc();
  861. // Suppress this diagnostic.
  862. ++NumSFINAEErrors;
  863. // Make a copy of this suppressed diagnostic and store it with the
  864. // template-deduction information.
  865. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  866. Diagnostic DiagInfo(&Diags);
  867. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  868. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  869. }
  870. Diags.setLastDiagnosticIgnored();
  871. Diags.Clear();
  872. // Now the diagnostic state is clear, produce a C++98 compatibility
  873. // warning.
  874. Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
  875. // The last diagnostic which Sema produced was ignored. Suppress any
  876. // notes attached to it.
  877. Diags.setLastDiagnosticIgnored();
  878. return;
  879. }
  880. case DiagnosticIDs::SFINAE_Suppress:
  881. // Make a copy of this suppressed diagnostic and store it with the
  882. // template-deduction information;
  883. if (*Info) {
  884. Diagnostic DiagInfo(&Diags);
  885. (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
  886. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  887. }
  888. // Suppress this diagnostic.
  889. Diags.setLastDiagnosticIgnored();
  890. Diags.Clear();
  891. return;
  892. }
  893. }
  894. // Set up the context's printing policy based on our current state.
  895. Context.setPrintingPolicy(getPrintingPolicy());
  896. // Emit the diagnostic.
  897. if (!Diags.EmitCurrentDiagnostic())
  898. return;
  899. // If this is not a note, and we're in a template instantiation
  900. // that is different from the last template instantiation where
  901. // we emitted an error, print a template instantiation
  902. // backtrace.
  903. if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
  904. !ActiveTemplateInstantiations.empty() &&
  905. ActiveTemplateInstantiations.back()
  906. != LastTemplateInstantiationErrorContext) {
  907. PrintInstantiationStack();
  908. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back();
  909. }
  910. }
  911. Sema::SemaDiagnosticBuilder
  912. Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
  913. SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
  914. PD.Emit(Builder);
  915. return Builder;
  916. }
  917. /// \brief Looks through the macro-expansion chain for the given
  918. /// location, looking for a macro expansion with the given name.
  919. /// If one is found, returns true and sets the location to that
  920. /// expansion loc.
  921. bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
  922. SourceLocation loc = locref;
  923. if (!loc.isMacroID()) return false;
  924. // There's no good way right now to look at the intermediate
  925. // expansions, so just jump to the expansion location.
  926. loc = getSourceManager().getExpansionLoc(loc);
  927. // If that's written with the name, stop here.
  928. SmallVector<char, 16> buffer;
  929. if (getPreprocessor().getSpelling(loc, buffer) == name) {
  930. locref = loc;
  931. return true;
  932. }
  933. return false;
  934. }
  935. /// \brief Determines the active Scope associated with the given declaration
  936. /// context.
  937. ///
  938. /// This routine maps a declaration context to the active Scope object that
  939. /// represents that declaration context in the parser. It is typically used
  940. /// from "scope-less" code (e.g., template instantiation, lazy creation of
  941. /// declarations) that injects a name for name-lookup purposes and, therefore,
  942. /// must update the Scope.
  943. ///
  944. /// \returns The scope corresponding to the given declaraion context, or NULL
  945. /// if no such scope is open.
  946. Scope *Sema::getScopeForContext(DeclContext *Ctx) {
  947. if (!Ctx)
  948. return nullptr;
  949. Ctx = Ctx->getPrimaryContext();
  950. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  951. // Ignore scopes that cannot have declarations. This is important for
  952. // out-of-line definitions of static class members.
  953. if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
  954. if (DeclContext *Entity = S->getEntity())
  955. if (Ctx == Entity->getPrimaryContext())
  956. return S;
  957. }
  958. return nullptr;
  959. }
  960. /// \brief Enter a new function scope
  961. void Sema::PushFunctionScope() {
  962. if (FunctionScopes.size() == 1) {
  963. // Use the "top" function scope rather than having to allocate
  964. // memory for a new scope.
  965. FunctionScopes.back()->Clear();
  966. FunctionScopes.push_back(FunctionScopes.back());
  967. return;
  968. }
  969. FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
  970. }
  971. void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
  972. FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
  973. BlockScope, Block));
  974. }
  975. LambdaScopeInfo *Sema::PushLambdaScope() {
  976. LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
  977. FunctionScopes.push_back(LSI);
  978. return LSI;
  979. }
  980. void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
  981. if (LambdaScopeInfo *const LSI = getCurLambda()) {
  982. LSI->AutoTemplateParameterDepth = Depth;
  983. return;
  984. }
  985. llvm_unreachable(
  986. "Remove assertion if intentionally called in a non-lambda context.");
  987. }
  988. void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
  989. const Decl *D, const BlockExpr *blkExpr) {
  990. FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
  991. assert(!FunctionScopes.empty() && "mismatched push/pop!");
  992. // Issue any analysis-based warnings.
  993. if (WP && D)
  994. AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
  995. else
  996. for (const auto &PUD : Scope->PossiblyUnreachableDiags)
  997. Diag(PUD.Loc, PUD.PD);
  998. if (FunctionScopes.back() != Scope)
  999. delete Scope;
  1000. }
  1001. void Sema::PushCompoundScope() {
  1002. getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
  1003. }
  1004. void Sema::PopCompoundScope() {
  1005. FunctionScopeInfo *CurFunction = getCurFunction();
  1006. assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
  1007. CurFunction->CompoundScopes.pop_back();
  1008. }
  1009. /// \brief Determine whether any errors occurred within this function/method/
  1010. /// block.
  1011. bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
  1012. return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
  1013. }
  1014. BlockScopeInfo *Sema::getCurBlock() {
  1015. if (FunctionScopes.empty())
  1016. return nullptr;
  1017. auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
  1018. if (CurBSI && CurBSI->TheDecl &&
  1019. !CurBSI->TheDecl->Encloses(CurContext)) {
  1020. // We have switched contexts due to template instantiation.
  1021. assert(!ActiveTemplateInstantiations.empty());
  1022. return nullptr;
  1023. }
  1024. return CurBSI;
  1025. }
  1026. LambdaScopeInfo *Sema::getCurLambda() {
  1027. if (FunctionScopes.empty())
  1028. return nullptr;
  1029. auto CurLSI = dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
  1030. if (CurLSI && CurLSI->Lambda &&
  1031. !CurLSI->Lambda->Encloses(CurContext)) {
  1032. // We have switched contexts due to template instantiation.
  1033. assert(!ActiveTemplateInstantiations.empty());
  1034. return nullptr;
  1035. }
  1036. return CurLSI;
  1037. }
  1038. // We have a generic lambda if we parsed auto parameters, or we have
  1039. // an associated template parameter list.
  1040. LambdaScopeInfo *Sema::getCurGenericLambda() {
  1041. if (LambdaScopeInfo *LSI = getCurLambda()) {
  1042. return (LSI->AutoTemplateParams.size() ||
  1043. LSI->GLTemplateParameterList) ? LSI : nullptr;
  1044. }
  1045. return nullptr;
  1046. }
  1047. void Sema::ActOnComment(SourceRange Comment) {
  1048. if (!LangOpts.RetainCommentsFromSystemHeaders &&
  1049. SourceMgr.isInSystemHeader(Comment.getBegin()))
  1050. return;
  1051. RawComment RC(SourceMgr, Comment, false,
  1052. LangOpts.CommentOpts.ParseAllComments);
  1053. if (RC.isAlmostTrailingComment()) {
  1054. SourceRange MagicMarkerRange(Comment.getBegin(),
  1055. Comment.getBegin().getLocWithOffset(3));
  1056. StringRef MagicMarkerText;
  1057. switch (RC.getKind()) {
  1058. case RawComment::RCK_OrdinaryBCPL:
  1059. MagicMarkerText = "///<";
  1060. break;
  1061. case RawComment::RCK_OrdinaryC:
  1062. MagicMarkerText = "/**<";
  1063. break;
  1064. default:
  1065. llvm_unreachable("if this is an almost Doxygen comment, "
  1066. "it should be ordinary");
  1067. }
  1068. Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
  1069. FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
  1070. }
  1071. Context.addComment(RC);
  1072. }
  1073. // Pin this vtable to this file.
  1074. ExternalSemaSource::~ExternalSemaSource() {}
  1075. void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
  1076. void ExternalSemaSource::ReadKnownNamespaces(
  1077. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  1078. }
  1079. void ExternalSemaSource::ReadUndefinedButUsed(
  1080. llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) {
  1081. }
  1082. void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
  1083. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
  1084. void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
  1085. SourceLocation Loc = this->Loc;
  1086. if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
  1087. if (Loc.isValid()) {
  1088. Loc.print(OS, S.getSourceManager());
  1089. OS << ": ";
  1090. }
  1091. OS << Message;
  1092. if (TheDecl && isa<NamedDecl>(TheDecl)) {
  1093. std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
  1094. if (!Name.empty())
  1095. OS << " '" << Name << '\'';
  1096. }
  1097. OS << '\n';
  1098. }
  1099. /// \brief Figure out if an expression could be turned into a call.
  1100. ///
  1101. /// Use this when trying to recover from an error where the programmer may have
  1102. /// written just the name of a function instead of actually calling it.
  1103. ///
  1104. /// \param E - The expression to examine.
  1105. /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
  1106. /// with no arguments, this parameter is set to the type returned by such a
  1107. /// call; otherwise, it is set to an empty QualType.
  1108. /// \param OverloadSet - If the expression is an overloaded function
  1109. /// name, this parameter is populated with the decls of the various overloads.
  1110. bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
  1111. UnresolvedSetImpl &OverloadSet) {
  1112. ZeroArgCallReturnTy = QualType();
  1113. OverloadSet.clear();
  1114. const OverloadExpr *Overloads = nullptr;
  1115. bool IsMemExpr = false;
  1116. if (E.getType() == Context.OverloadTy) {
  1117. OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
  1118. // Ignore overloads that are pointer-to-member constants.
  1119. if (FR.HasFormOfMemberPointer)
  1120. return false;
  1121. Overloads = FR.Expression;
  1122. } else if (E.getType() == Context.BoundMemberTy) {
  1123. Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
  1124. IsMemExpr = true;
  1125. }
  1126. bool Ambiguous = false;
  1127. if (Overloads) {
  1128. for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
  1129. DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
  1130. OverloadSet.addDecl(*it);
  1131. // Check whether the function is a non-template, non-member which takes no
  1132. // arguments.
  1133. if (IsMemExpr)
  1134. continue;
  1135. if (const FunctionDecl *OverloadDecl
  1136. = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
  1137. if (OverloadDecl->getMinRequiredArguments() == 0) {
  1138. if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
  1139. ZeroArgCallReturnTy = QualType();
  1140. Ambiguous = true;
  1141. } else
  1142. ZeroArgCallReturnTy = OverloadDecl->getReturnType();
  1143. }
  1144. }
  1145. }
  1146. // If it's not a member, use better machinery to try to resolve the call
  1147. if (!IsMemExpr)
  1148. return !ZeroArgCallReturnTy.isNull();
  1149. }
  1150. // Attempt to call the member with no arguments - this will correctly handle
  1151. // member templates with defaults/deduction of template arguments, overloads
  1152. // with default arguments, etc.
  1153. if (IsMemExpr && !E.isTypeDependent()) {
  1154. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  1155. getDiagnostics().setSuppressAllDiagnostics(true);
  1156. ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
  1157. None, SourceLocation());
  1158. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  1159. if (R.isUsable()) {
  1160. ZeroArgCallReturnTy = R.get()->getType();
  1161. return true;
  1162. }
  1163. return false;
  1164. }
  1165. if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
  1166. if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
  1167. if (Fun->getMinRequiredArguments() == 0)
  1168. ZeroArgCallReturnTy = Fun->getReturnType();
  1169. return true;
  1170. }
  1171. }
  1172. // We don't have an expression that's convenient to get a FunctionDecl from,
  1173. // but we can at least check if the type is "function of 0 arguments".
  1174. QualType ExprTy = E.getType();
  1175. const FunctionType *FunTy = nullptr;
  1176. QualType PointeeTy = ExprTy->getPointeeType();
  1177. if (!PointeeTy.isNull())
  1178. FunTy = PointeeTy->getAs<FunctionType>();
  1179. if (!FunTy)
  1180. FunTy = ExprTy->getAs<FunctionType>();
  1181. if (const FunctionProtoType *FPT =
  1182. dyn_cast_or_null<FunctionProtoType>(FunTy)) {
  1183. if (FPT->getNumParams() == 0)
  1184. ZeroArgCallReturnTy = FunTy->getReturnType();
  1185. return true;
  1186. }
  1187. return false;
  1188. }
  1189. /// \brief Give notes for a set of overloads.
  1190. ///
  1191. /// A companion to tryExprAsCall. In cases when the name that the programmer
  1192. /// wrote was an overloaded function, we may be able to make some guesses about
  1193. /// plausible overloads based on their return types; such guesses can be handed
  1194. /// off to this method to be emitted as notes.
  1195. ///
  1196. /// \param Overloads - The overloads to note.
  1197. /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
  1198. /// -fshow-overloads=best, this is the location to attach to the note about too
  1199. /// many candidates. Typically this will be the location of the original
  1200. /// ill-formed expression.
  1201. static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
  1202. const SourceLocation FinalNoteLoc) {
  1203. int ShownOverloads = 0;
  1204. int SuppressedOverloads = 0;
  1205. for (UnresolvedSetImpl::iterator It = Overloads.begin(),
  1206. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1207. // FIXME: Magic number for max shown overloads stolen from
  1208. // OverloadCandidateSet::NoteCandidates.
  1209. if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
  1210. ++SuppressedOverloads;
  1211. continue;
  1212. }
  1213. NamedDecl *Fn = (*It)->getUnderlyingDecl();
  1214. if (!Fn->getLocation().isValid()) continue; // HLSL Change: skip built-in locations
  1215. S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
  1216. ++ShownOverloads;
  1217. }
  1218. if (SuppressedOverloads)
  1219. S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
  1220. << SuppressedOverloads;
  1221. }
  1222. static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
  1223. const UnresolvedSetImpl &Overloads,
  1224. bool (*IsPlausibleResult)(QualType)) {
  1225. if (!IsPlausibleResult)
  1226. return noteOverloads(S, Overloads, Loc);
  1227. UnresolvedSet<2> PlausibleOverloads;
  1228. for (OverloadExpr::decls_iterator It = Overloads.begin(),
  1229. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1230. const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
  1231. QualType OverloadResultTy = OverloadDecl->getReturnType();
  1232. if (IsPlausibleResult(OverloadResultTy))
  1233. PlausibleOverloads.addDecl(It.getDecl());
  1234. }
  1235. noteOverloads(S, PlausibleOverloads, Loc);
  1236. }
  1237. /// Determine whether the given expression can be called by just
  1238. /// putting parentheses after it. Notably, expressions with unary
  1239. /// operators can't be because the unary operator will start parsing
  1240. /// outside the call.
  1241. static bool IsCallableWithAppend(Expr *E) {
  1242. E = E->IgnoreImplicit();
  1243. return (!isa<CStyleCastExpr>(E) &&
  1244. !isa<UnaryOperator>(E) &&
  1245. !isa<BinaryOperator>(E) &&
  1246. !isa<CXXOperatorCallExpr>(E));
  1247. }
  1248. bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
  1249. bool ForceComplain,
  1250. bool (*IsPlausibleResult)(QualType)) {
  1251. SourceLocation Loc = E.get()->getExprLoc();
  1252. SourceRange Range = E.get()->getSourceRange();
  1253. QualType ZeroArgCallTy;
  1254. UnresolvedSet<4> Overloads;
  1255. if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
  1256. !ZeroArgCallTy.isNull() &&
  1257. (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
  1258. // At this point, we know E is potentially callable with 0
  1259. // arguments and that it returns something of a reasonable type,
  1260. // so we can emit a fixit and carry on pretending that E was
  1261. // actually a CallExpr.
  1262. SourceLocation ParenInsertionLoc = PP.getLocForEndOfToken(Range.getEnd());
  1263. Diag(Loc, PD)
  1264. << /*zero-arg*/ 1 << Range
  1265. << (IsCallableWithAppend(E.get())
  1266. ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
  1267. : FixItHint());
  1268. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1269. // FIXME: Try this before emitting the fixit, and suppress diagnostics
  1270. // while doing so.
  1271. E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
  1272. Range.getEnd().getLocWithOffset(1));
  1273. return true;
  1274. }
  1275. if (!ForceComplain) return false;
  1276. Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
  1277. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1278. E = ExprError();
  1279. return true;
  1280. }
  1281. IdentifierInfo *Sema::getSuperIdentifier() const {
  1282. if (!Ident_super)
  1283. Ident_super = &Context.Idents.get("super");
  1284. return Ident_super;
  1285. }
  1286. IdentifierInfo *Sema::getFloat128Identifier() const {
  1287. if (!Ident___float128)
  1288. Ident___float128 = &Context.Idents.get("__float128");
  1289. return Ident___float128;
  1290. }
  1291. void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
  1292. CapturedRegionKind K) {
  1293. CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
  1294. getDiagnostics(), S, CD, RD, CD->getContextParam(), K);
  1295. CSI->ReturnType = Context.VoidTy;
  1296. FunctionScopes.push_back(CSI);
  1297. }
  1298. CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
  1299. if (FunctionScopes.empty())
  1300. return nullptr;
  1301. return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
  1302. }
  1303. const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
  1304. Sema::getMismatchingDeleteExpressions() const {
  1305. return DeleteExprs;
  1306. }