Sema.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252
  1. //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the actions class which performs semantic analysis and
  10. // builds an AST out of a parse stream.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTDiagnostic.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclFriend.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/PrettyDeclStackTrace.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/Basic/DiagnosticOptions.h"
  23. #include "clang/Basic/PartialDiagnostic.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Lex/HeaderSearch.h"
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "clang/Sema/CXXFieldCollector.h"
  28. #include "clang/Sema/DelayedDiagnostic.h"
  29. #include "clang/Sema/ExternalSemaSource.h"
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/MultiplexExternalSemaSource.h"
  32. #include "clang/Sema/ObjCMethodList.h"
  33. #include "clang/Sema/Scope.h"
  34. #include "clang/Sema/ScopeInfo.h"
  35. #include "clang/Sema/SemaConsumer.h"
  36. #include "clang/Sema/SemaInternal.h"
  37. #include "clang/Sema/TemplateDeduction.h"
  38. #include "clang/Sema/TemplateInstCallback.h"
  39. #include "llvm/ADT/DenseMap.h"
  40. #include "llvm/ADT/SmallSet.h"
  41. #include "llvm/Support/TimeProfiler.h"
  42. using namespace clang;
  43. using namespace sema;
  44. SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
  45. return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
  46. }
  47. ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
  48. PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
  49. const Preprocessor &PP) {
  50. PrintingPolicy Policy = Context.getPrintingPolicy();
  51. // In diagnostics, we print _Bool as bool if the latter is defined as the
  52. // former.
  53. Policy.Bool = Context.getLangOpts().Bool;
  54. if (!Policy.Bool) {
  55. if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
  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. namespace clang {
  68. namespace sema {
  69. class SemaPPCallbacks : public PPCallbacks {
  70. Sema *S = nullptr;
  71. llvm::SmallVector<SourceLocation, 8> IncludeStack;
  72. public:
  73. void set(Sema &S) { this->S = &S; }
  74. void reset() { S = nullptr; }
  75. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  76. SrcMgr::CharacteristicKind FileType,
  77. FileID PrevFID) override {
  78. if (!S)
  79. return;
  80. switch (Reason) {
  81. case EnterFile: {
  82. SourceManager &SM = S->getSourceManager();
  83. SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
  84. if (IncludeLoc.isValid()) {
  85. if (llvm::timeTraceProfilerEnabled()) {
  86. const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
  87. llvm::timeTraceProfilerBegin(
  88. "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
  89. }
  90. IncludeStack.push_back(IncludeLoc);
  91. S->DiagnoseNonDefaultPragmaPack(
  92. Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
  93. }
  94. break;
  95. }
  96. case ExitFile:
  97. if (!IncludeStack.empty()) {
  98. if (llvm::timeTraceProfilerEnabled())
  99. llvm::timeTraceProfilerEnd();
  100. S->DiagnoseNonDefaultPragmaPack(
  101. Sema::PragmaPackDiagnoseKind::ChangedStateAtExit,
  102. IncludeStack.pop_back_val());
  103. }
  104. break;
  105. default:
  106. break;
  107. }
  108. }
  109. };
  110. } // end namespace sema
  111. } // end namespace clang
  112. Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
  113. TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
  114. : ExternalSource(nullptr), isMultiplexExternalSource(false),
  115. FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
  116. Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
  117. SourceMgr(PP.getSourceManager()), CollectStats(false),
  118. CodeCompleter(CodeCompleter), CurContext(nullptr),
  119. OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
  120. MSPointerToMemberRepresentationMethod(
  121. LangOpts.getMSPointerToMemberRepresentationMethod()),
  122. VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
  123. DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
  124. CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
  125. PragmaAttributeCurrentTargetDecl(nullptr),
  126. IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
  127. LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
  128. StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
  129. StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
  130. MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr),
  131. NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
  132. ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
  133. ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
  134. DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
  135. TUKind(TUKind), NumSFINAEErrors(0),
  136. FullyCheckedComparisonCategories(
  137. static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
  138. AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
  139. NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
  140. CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
  141. TyposCorrected(0), AnalysisWarnings(*this),
  142. ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
  143. CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
  144. TUScope = nullptr;
  145. isConstantEvaluatedOverride = false;
  146. LoadedExternalKnownNamespaces = false;
  147. for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
  148. NSNumberLiteralMethods[I] = nullptr;
  149. if (getLangOpts().ObjC)
  150. NSAPIObj.reset(new NSAPI(Context));
  151. if (getLangOpts().CPlusPlus)
  152. FieldCollector.reset(new CXXFieldCollector());
  153. // Tell diagnostics how to render things from the AST library.
  154. Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
  155. ExprEvalContexts.emplace_back(
  156. ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
  157. nullptr, ExpressionEvaluationContextRecord::EK_Other);
  158. // Initialization of data sharing attributes stack for OpenMP
  159. InitDataSharingAttributesStack();
  160. std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
  161. llvm::make_unique<sema::SemaPPCallbacks>();
  162. SemaPPCallbackHandler = Callbacks.get();
  163. PP.addPPCallbacks(std::move(Callbacks));
  164. SemaPPCallbackHandler->set(*this);
  165. }
  166. void Sema::addImplicitTypedef(StringRef Name, QualType T) {
  167. DeclarationName DN = &Context.Idents.get(Name);
  168. if (IdResolver.begin(DN) == IdResolver.end())
  169. PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
  170. }
  171. void Sema::Initialize() {
  172. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  173. SC->InitializeSema(*this);
  174. // Tell the external Sema source about this Sema object.
  175. if (ExternalSemaSource *ExternalSema
  176. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  177. ExternalSema->InitializeSema(*this);
  178. // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
  179. // will not be able to merge any duplicate __va_list_tag decls correctly.
  180. VAListTagName = PP.getIdentifierInfo("__va_list_tag");
  181. if (!TUScope)
  182. return;
  183. // Initialize predefined 128-bit integer types, if needed.
  184. if (Context.getTargetInfo().hasInt128Type()) {
  185. // If either of the 128-bit integer types are unavailable to name lookup,
  186. // define them now.
  187. DeclarationName Int128 = &Context.Idents.get("__int128_t");
  188. if (IdResolver.begin(Int128) == IdResolver.end())
  189. PushOnScopeChains(Context.getInt128Decl(), TUScope);
  190. DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
  191. if (IdResolver.begin(UInt128) == IdResolver.end())
  192. PushOnScopeChains(Context.getUInt128Decl(), TUScope);
  193. }
  194. // Initialize predefined Objective-C types:
  195. if (getLangOpts().ObjC) {
  196. // If 'SEL' does not yet refer to any declarations, make it refer to the
  197. // predefined 'SEL'.
  198. DeclarationName SEL = &Context.Idents.get("SEL");
  199. if (IdResolver.begin(SEL) == IdResolver.end())
  200. PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
  201. // If 'id' does not yet refer to any declarations, make it refer to the
  202. // predefined 'id'.
  203. DeclarationName Id = &Context.Idents.get("id");
  204. if (IdResolver.begin(Id) == IdResolver.end())
  205. PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
  206. // Create the built-in typedef for 'Class'.
  207. DeclarationName Class = &Context.Idents.get("Class");
  208. if (IdResolver.begin(Class) == IdResolver.end())
  209. PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
  210. // Create the built-in forward declaratino for 'Protocol'.
  211. DeclarationName Protocol = &Context.Idents.get("Protocol");
  212. if (IdResolver.begin(Protocol) == IdResolver.end())
  213. PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
  214. }
  215. // Create the internal type for the *StringMakeConstantString builtins.
  216. DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
  217. if (IdResolver.begin(ConstantString) == IdResolver.end())
  218. PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
  219. // Initialize Microsoft "predefined C++ types".
  220. if (getLangOpts().MSVCCompat) {
  221. if (getLangOpts().CPlusPlus &&
  222. IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
  223. PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
  224. TUScope);
  225. addImplicitTypedef("size_t", Context.getSizeType());
  226. }
  227. // Initialize predefined OpenCL types and supported extensions and (optional)
  228. // core features.
  229. if (getLangOpts().OpenCL) {
  230. getOpenCLOptions().addSupport(
  231. Context.getTargetInfo().getSupportedOpenCLOpts());
  232. getOpenCLOptions().enableSupportedCore(getLangOpts());
  233. addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
  234. addImplicitTypedef("event_t", Context.OCLEventTy);
  235. if (getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) {
  236. addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
  237. addImplicitTypedef("queue_t", Context.OCLQueueTy);
  238. addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
  239. addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
  240. addImplicitTypedef("atomic_uint",
  241. Context.getAtomicType(Context.UnsignedIntTy));
  242. auto AtomicLongT = Context.getAtomicType(Context.LongTy);
  243. addImplicitTypedef("atomic_long", AtomicLongT);
  244. auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
  245. addImplicitTypedef("atomic_ulong", AtomicULongT);
  246. addImplicitTypedef("atomic_float",
  247. Context.getAtomicType(Context.FloatTy));
  248. auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
  249. addImplicitTypedef("atomic_double", AtomicDoubleT);
  250. // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
  251. // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
  252. addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
  253. auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
  254. addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
  255. auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
  256. addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
  257. auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
  258. addImplicitTypedef("atomic_size_t", AtomicSizeT);
  259. auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
  260. addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
  261. // OpenCL v2.0 s6.13.11.6:
  262. // - The atomic_long and atomic_ulong types are supported if the
  263. // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
  264. // extensions are supported.
  265. // - The atomic_double type is only supported if double precision
  266. // is supported and the cl_khr_int64_base_atomics and
  267. // cl_khr_int64_extended_atomics extensions are supported.
  268. // - If the device address space is 64-bits, the data types
  269. // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
  270. // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
  271. // cl_khr_int64_extended_atomics extensions are supported.
  272. std::vector<QualType> Atomic64BitTypes;
  273. Atomic64BitTypes.push_back(AtomicLongT);
  274. Atomic64BitTypes.push_back(AtomicULongT);
  275. Atomic64BitTypes.push_back(AtomicDoubleT);
  276. if (Context.getTypeSize(AtomicSizeT) == 64) {
  277. Atomic64BitTypes.push_back(AtomicSizeT);
  278. Atomic64BitTypes.push_back(AtomicIntPtrT);
  279. Atomic64BitTypes.push_back(AtomicUIntPtrT);
  280. Atomic64BitTypes.push_back(AtomicPtrDiffT);
  281. }
  282. for (auto &I : Atomic64BitTypes)
  283. setOpenCLExtensionForType(I,
  284. "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
  285. setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
  286. }
  287. setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
  288. #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
  289. setOpenCLExtensionForType(Context.Id, Ext);
  290. #include "clang/Basic/OpenCLImageTypes.def"
  291. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  292. addImplicitTypedef(#ExtType, Context.Id##Ty); \
  293. setOpenCLExtensionForType(Context.Id##Ty, #Ext);
  294. #include "clang/Basic/OpenCLExtensionTypes.def"
  295. };
  296. if (Context.getTargetInfo().hasBuiltinMSVaList()) {
  297. DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
  298. if (IdResolver.begin(MSVaList) == IdResolver.end())
  299. PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
  300. }
  301. DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
  302. if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
  303. PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
  304. }
  305. Sema::~Sema() {
  306. if (VisContext) FreeVisContext();
  307. // Kill all the active scopes.
  308. for (sema::FunctionScopeInfo *FSI : FunctionScopes)
  309. delete FSI;
  310. // Tell the SemaConsumer to forget about us; we're going out of scope.
  311. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  312. SC->ForgetSema();
  313. // Detach from the external Sema source.
  314. if (ExternalSemaSource *ExternalSema
  315. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  316. ExternalSema->ForgetSema();
  317. // If Sema's ExternalSource is the multiplexer - we own it.
  318. if (isMultiplexExternalSource)
  319. delete ExternalSource;
  320. threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
  321. // Destroys data sharing attributes stack for OpenMP
  322. DestroyDataSharingAttributesStack();
  323. // Detach from the PP callback handler which outlives Sema since it's owned
  324. // by the preprocessor.
  325. SemaPPCallbackHandler->reset();
  326. assert(DelayedTypos.empty() && "Uncorrected typos!");
  327. }
  328. /// makeUnavailableInSystemHeader - There is an error in the current
  329. /// context. If we're still in a system header, and we can plausibly
  330. /// make the relevant declaration unavailable instead of erroring, do
  331. /// so and return true.
  332. bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
  333. UnavailableAttr::ImplicitReason reason) {
  334. // If we're not in a function, it's an error.
  335. FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
  336. if (!fn) return false;
  337. // If we're in template instantiation, it's an error.
  338. if (inTemplateInstantiation())
  339. return false;
  340. // If that function's not in a system header, it's an error.
  341. if (!Context.getSourceManager().isInSystemHeader(loc))
  342. return false;
  343. // If the function is already unavailable, it's not an error.
  344. if (fn->hasAttr<UnavailableAttr>()) return true;
  345. fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
  346. return true;
  347. }
  348. ASTMutationListener *Sema::getASTMutationListener() const {
  349. return getASTConsumer().GetASTMutationListener();
  350. }
  351. ///Registers an external source. If an external source already exists,
  352. /// creates a multiplex external source and appends to it.
  353. ///
  354. ///\param[in] E - A non-null external sema source.
  355. ///
  356. void Sema::addExternalSource(ExternalSemaSource *E) {
  357. assert(E && "Cannot use with NULL ptr");
  358. if (!ExternalSource) {
  359. ExternalSource = E;
  360. return;
  361. }
  362. if (isMultiplexExternalSource)
  363. static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
  364. else {
  365. ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
  366. isMultiplexExternalSource = true;
  367. }
  368. }
  369. /// Print out statistics about the semantic analysis.
  370. void Sema::PrintStats() const {
  371. llvm::errs() << "\n*** Semantic Analysis Stats:\n";
  372. llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
  373. BumpAlloc.PrintStats();
  374. AnalysisWarnings.PrintStats();
  375. }
  376. void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
  377. QualType SrcType,
  378. SourceLocation Loc) {
  379. Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
  380. if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
  381. return;
  382. Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
  383. if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
  384. return;
  385. Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
  386. }
  387. void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
  388. if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
  389. E->getBeginLoc()))
  390. return;
  391. // nullptr only exists from C++11 on, so don't warn on its absence earlier.
  392. if (!getLangOpts().CPlusPlus11)
  393. return;
  394. if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
  395. return;
  396. if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
  397. return;
  398. // If it is a macro from system header, and if the macro name is not "NULL",
  399. // do not warn.
  400. SourceLocation MaybeMacroLoc = E->getBeginLoc();
  401. if (Diags.getSuppressSystemWarnings() &&
  402. SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
  403. !findMacroSpelling(MaybeMacroLoc, "NULL"))
  404. return;
  405. Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
  406. << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
  407. }
  408. /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
  409. /// If there is already an implicit cast, merge into the existing one.
  410. /// The result is of the given category.
  411. ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
  412. CastKind Kind, ExprValueKind VK,
  413. const CXXCastPath *BasePath,
  414. CheckedConversionKind CCK) {
  415. #ifndef NDEBUG
  416. if (VK == VK_RValue && !E->isRValue()) {
  417. switch (Kind) {
  418. default:
  419. llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
  420. "kind");
  421. case CK_Dependent:
  422. case CK_LValueToRValue:
  423. case CK_ArrayToPointerDecay:
  424. case CK_FunctionToPointerDecay:
  425. case CK_ToVoid:
  426. case CK_NonAtomicToAtomic:
  427. break;
  428. }
  429. }
  430. assert((VK == VK_RValue || Kind == CK_Dependent || !E->isRValue()) &&
  431. "can't cast rvalue to lvalue");
  432. #endif
  433. diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
  434. diagnoseZeroToNullptrConversion(Kind, E);
  435. QualType ExprTy = Context.getCanonicalType(E->getType());
  436. QualType TypeTy = Context.getCanonicalType(Ty);
  437. if (ExprTy == TypeTy)
  438. return E;
  439. // C++1z [conv.array]: The temporary materialization conversion is applied.
  440. // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
  441. if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
  442. E->getValueKind() == VK_RValue) {
  443. // The temporary is an lvalue in C++98 and an xvalue otherwise.
  444. ExprResult Materialized = CreateMaterializeTemporaryExpr(
  445. E->getType(), E, !getLangOpts().CPlusPlus11);
  446. if (Materialized.isInvalid())
  447. return ExprError();
  448. E = Materialized.get();
  449. }
  450. if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  451. if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
  452. ImpCast->setType(Ty);
  453. ImpCast->setValueKind(VK);
  454. return E;
  455. }
  456. }
  457. return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
  458. }
  459. /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
  460. /// to the conversion from scalar type ScalarTy to the Boolean type.
  461. CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
  462. switch (ScalarTy->getScalarTypeKind()) {
  463. case Type::STK_Bool: return CK_NoOp;
  464. case Type::STK_CPointer: return CK_PointerToBoolean;
  465. case Type::STK_BlockPointer: return CK_PointerToBoolean;
  466. case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
  467. case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
  468. case Type::STK_Integral: return CK_IntegralToBoolean;
  469. case Type::STK_Floating: return CK_FloatingToBoolean;
  470. case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
  471. case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
  472. case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
  473. }
  474. llvm_unreachable("unknown scalar type kind");
  475. }
  476. /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
  477. static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
  478. if (D->getMostRecentDecl()->isUsed())
  479. return true;
  480. if (D->isExternallyVisible())
  481. return true;
  482. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  483. // If this is a function template and none of its specializations is used,
  484. // we should warn.
  485. if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
  486. for (const auto *Spec : Template->specializations())
  487. if (ShouldRemoveFromUnused(SemaRef, Spec))
  488. return true;
  489. // UnusedFileScopedDecls stores the first declaration.
  490. // The declaration may have become definition so check again.
  491. const FunctionDecl *DeclToCheck;
  492. if (FD->hasBody(DeclToCheck))
  493. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  494. // Later redecls may add new information resulting in not having to warn,
  495. // so check again.
  496. DeclToCheck = FD->getMostRecentDecl();
  497. if (DeclToCheck != FD)
  498. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  499. }
  500. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  501. // If a variable usable in constant expressions is referenced,
  502. // don't warn if it isn't used: if the value of a variable is required
  503. // for the computation of a constant expression, it doesn't make sense to
  504. // warn even if the variable isn't odr-used. (isReferenced doesn't
  505. // precisely reflect that, but it's a decent approximation.)
  506. if (VD->isReferenced() &&
  507. VD->mightBeUsableInConstantExpressions(SemaRef->Context))
  508. return true;
  509. if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
  510. // If this is a variable template and none of its specializations is used,
  511. // we should warn.
  512. for (const auto *Spec : Template->specializations())
  513. if (ShouldRemoveFromUnused(SemaRef, Spec))
  514. return true;
  515. // UnusedFileScopedDecls stores the first declaration.
  516. // The declaration may have become definition so check again.
  517. const VarDecl *DeclToCheck = VD->getDefinition();
  518. if (DeclToCheck)
  519. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  520. // Later redecls may add new information resulting in not having to warn,
  521. // so check again.
  522. DeclToCheck = VD->getMostRecentDecl();
  523. if (DeclToCheck != VD)
  524. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  525. }
  526. return false;
  527. }
  528. static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
  529. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  530. return FD->isExternC();
  531. return cast<VarDecl>(ND)->isExternC();
  532. }
  533. /// Determine whether ND is an external-linkage function or variable whose
  534. /// type has no linkage.
  535. bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
  536. // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
  537. // because we also want to catch the case where its type has VisibleNoLinkage,
  538. // which does not affect the linkage of VD.
  539. return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
  540. !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
  541. !isFunctionOrVarDeclExternC(VD);
  542. }
  543. /// Obtains a sorted list of functions and variables that are undefined but
  544. /// ODR-used.
  545. void Sema::getUndefinedButUsed(
  546. SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
  547. for (const auto &UndefinedUse : UndefinedButUsed) {
  548. NamedDecl *ND = UndefinedUse.first;
  549. // Ignore attributes that have become invalid.
  550. if (ND->isInvalidDecl()) continue;
  551. // __attribute__((weakref)) is basically a definition.
  552. if (ND->hasAttr<WeakRefAttr>()) continue;
  553. if (isa<CXXDeductionGuideDecl>(ND))
  554. continue;
  555. if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
  556. // An exported function will always be emitted when defined, so even if
  557. // the function is inline, it doesn't have to be emitted in this TU. An
  558. // imported function implies that it has been exported somewhere else.
  559. continue;
  560. }
  561. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  562. if (FD->isDefined())
  563. continue;
  564. if (FD->isExternallyVisible() &&
  565. !isExternalWithNoLinkageType(FD) &&
  566. !FD->getMostRecentDecl()->isInlined() &&
  567. !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  568. continue;
  569. if (FD->getBuiltinID())
  570. continue;
  571. } else {
  572. auto *VD = cast<VarDecl>(ND);
  573. if (VD->hasDefinition() != VarDecl::DeclarationOnly)
  574. continue;
  575. if (VD->isExternallyVisible() &&
  576. !isExternalWithNoLinkageType(VD) &&
  577. !VD->getMostRecentDecl()->isInline() &&
  578. !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  579. continue;
  580. // Skip VarDecls that lack formal definitions but which we know are in
  581. // fact defined somewhere.
  582. if (VD->isKnownToBeDefined())
  583. continue;
  584. }
  585. Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
  586. }
  587. }
  588. /// checkUndefinedButUsed - Check for undefined objects with internal linkage
  589. /// or that are inline.
  590. static void checkUndefinedButUsed(Sema &S) {
  591. if (S.UndefinedButUsed.empty()) return;
  592. // Collect all the still-undefined entities with internal linkage.
  593. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  594. S.getUndefinedButUsed(Undefined);
  595. if (Undefined.empty()) return;
  596. for (auto Undef : Undefined) {
  597. ValueDecl *VD = cast<ValueDecl>(Undef.first);
  598. SourceLocation UseLoc = Undef.second;
  599. if (S.isExternalWithNoLinkageType(VD)) {
  600. // C++ [basic.link]p8:
  601. // A type without linkage shall not be used as the type of a variable
  602. // or function with external linkage unless
  603. // -- the entity has C language linkage
  604. // -- the entity is not odr-used or is defined in the same TU
  605. //
  606. // As an extension, accept this in cases where the type is externally
  607. // visible, since the function or variable actually can be defined in
  608. // another translation unit in that case.
  609. S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
  610. ? diag::ext_undefined_internal_type
  611. : diag::err_undefined_internal_type)
  612. << isa<VarDecl>(VD) << VD;
  613. } else if (!VD->isExternallyVisible()) {
  614. // FIXME: We can promote this to an error. The function or variable can't
  615. // be defined anywhere else, so the program must necessarily violate the
  616. // one definition rule.
  617. S.Diag(VD->getLocation(), diag::warn_undefined_internal)
  618. << isa<VarDecl>(VD) << VD;
  619. } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
  620. (void)FD;
  621. assert(FD->getMostRecentDecl()->isInlined() &&
  622. "used object requires definition but isn't inline or internal?");
  623. // FIXME: This is ill-formed; we should reject.
  624. S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
  625. } else {
  626. assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
  627. "used var requires definition but isn't inline or internal?");
  628. S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
  629. }
  630. if (UseLoc.isValid())
  631. S.Diag(UseLoc, diag::note_used_here);
  632. }
  633. S.UndefinedButUsed.clear();
  634. }
  635. void Sema::LoadExternalWeakUndeclaredIdentifiers() {
  636. if (!ExternalSource)
  637. return;
  638. SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
  639. ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
  640. for (auto &WeakID : WeakIDs)
  641. WeakUndeclaredIdentifiers.insert(WeakID);
  642. }
  643. typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
  644. /// Returns true, if all methods and nested classes of the given
  645. /// CXXRecordDecl are defined in this translation unit.
  646. ///
  647. /// Should only be called from ActOnEndOfTranslationUnit so that all
  648. /// definitions are actually read.
  649. static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
  650. RecordCompleteMap &MNCComplete) {
  651. RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
  652. if (Cache != MNCComplete.end())
  653. return Cache->second;
  654. if (!RD->isCompleteDefinition())
  655. return false;
  656. bool Complete = true;
  657. for (DeclContext::decl_iterator I = RD->decls_begin(),
  658. E = RD->decls_end();
  659. I != E && Complete; ++I) {
  660. if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
  661. Complete = M->isDefined() || M->isDefaulted() ||
  662. (M->isPure() && !isa<CXXDestructorDecl>(M));
  663. else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
  664. // If the template function is marked as late template parsed at this
  665. // point, it has not been instantiated and therefore we have not
  666. // performed semantic analysis on it yet, so we cannot know if the type
  667. // can be considered complete.
  668. Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
  669. F->getTemplatedDecl()->isDefined();
  670. else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
  671. if (R->isInjectedClassName())
  672. continue;
  673. if (R->hasDefinition())
  674. Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
  675. MNCComplete);
  676. else
  677. Complete = false;
  678. }
  679. }
  680. MNCComplete[RD] = Complete;
  681. return Complete;
  682. }
  683. /// Returns true, if the given CXXRecordDecl is fully defined in this
  684. /// translation unit, i.e. all methods are defined or pure virtual and all
  685. /// friends, friend functions and nested classes are fully defined in this
  686. /// translation unit.
  687. ///
  688. /// Should only be called from ActOnEndOfTranslationUnit so that all
  689. /// definitions are actually read.
  690. static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
  691. RecordCompleteMap &RecordsComplete,
  692. RecordCompleteMap &MNCComplete) {
  693. RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
  694. if (Cache != RecordsComplete.end())
  695. return Cache->second;
  696. bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
  697. for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
  698. E = RD->friend_end();
  699. I != E && Complete; ++I) {
  700. // Check if friend classes and methods are complete.
  701. if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
  702. // Friend classes are available as the TypeSourceInfo of the FriendDecl.
  703. if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
  704. Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
  705. else
  706. Complete = false;
  707. } else {
  708. // Friend functions are available through the NamedDecl of FriendDecl.
  709. if (const FunctionDecl *FD =
  710. dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
  711. Complete = FD->isDefined();
  712. else
  713. // This is a template friend, give up.
  714. Complete = false;
  715. }
  716. }
  717. RecordsComplete[RD] = Complete;
  718. return Complete;
  719. }
  720. void Sema::emitAndClearUnusedLocalTypedefWarnings() {
  721. if (ExternalSource)
  722. ExternalSource->ReadUnusedLocalTypedefNameCandidates(
  723. UnusedLocalTypedefNameCandidates);
  724. for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
  725. if (TD->isReferenced())
  726. continue;
  727. Diag(TD->getLocation(), diag::warn_unused_local_typedef)
  728. << isa<TypeAliasDecl>(TD) << TD->getDeclName();
  729. }
  730. UnusedLocalTypedefNameCandidates.clear();
  731. }
  732. /// This is called before the very first declaration in the translation unit
  733. /// is parsed. Note that the ASTContext may have already injected some
  734. /// declarations.
  735. void Sema::ActOnStartOfTranslationUnit() {
  736. if (getLangOpts().ModulesTS &&
  737. (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface ||
  738. getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
  739. // We start in an implied global module fragment.
  740. SourceLocation StartOfTU =
  741. SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  742. ActOnGlobalModuleFragmentDecl(StartOfTU);
  743. ModuleScopes.back().ImplicitGlobalModuleFragment = true;
  744. }
  745. }
  746. void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
  747. // No explicit actions are required at the end of the global module fragment.
  748. if (Kind == TUFragmentKind::Global)
  749. return;
  750. // Transfer late parsed template instantiations over to the pending template
  751. // instantiation list. During normal compilation, the late template parser
  752. // will be installed and instantiating these templates will succeed.
  753. //
  754. // If we are building a TU prefix for serialization, it is also safe to
  755. // transfer these over, even though they are not parsed. The end of the TU
  756. // should be outside of any eager template instantiation scope, so when this
  757. // AST is deserialized, these templates will not be parsed until the end of
  758. // the combined TU.
  759. PendingInstantiations.insert(PendingInstantiations.end(),
  760. LateParsedInstantiations.begin(),
  761. LateParsedInstantiations.end());
  762. LateParsedInstantiations.clear();
  763. // If DefinedUsedVTables ends up marking any virtual member functions it
  764. // might lead to more pending template instantiations, which we then need
  765. // to instantiate.
  766. DefineUsedVTables();
  767. // C++: Perform implicit template instantiations.
  768. //
  769. // FIXME: When we perform these implicit instantiations, we do not
  770. // carefully keep track of the point of instantiation (C++ [temp.point]).
  771. // This means that name lookup that occurs within the template
  772. // instantiation will always happen at the end of the translation unit,
  773. // so it will find some names that are not required to be found. This is
  774. // valid, but we could do better by diagnosing if an instantiation uses a
  775. // name that was not visible at its first point of instantiation.
  776. if (ExternalSource) {
  777. // Load pending instantiations from the external source.
  778. SmallVector<PendingImplicitInstantiation, 4> Pending;
  779. ExternalSource->ReadPendingInstantiations(Pending);
  780. for (auto PII : Pending)
  781. if (auto Func = dyn_cast<FunctionDecl>(PII.first))
  782. Func->setInstantiationIsPending(true);
  783. PendingInstantiations.insert(PendingInstantiations.begin(),
  784. Pending.begin(), Pending.end());
  785. }
  786. {
  787. llvm::TimeTraceScope TimeScope("PerformPendingInstantiations",
  788. StringRef(""));
  789. PerformPendingInstantiations();
  790. }
  791. assert(LateParsedInstantiations.empty() &&
  792. "end of TU template instantiation should not create more "
  793. "late-parsed templates");
  794. }
  795. /// ActOnEndOfTranslationUnit - This is called at the very end of the
  796. /// translation unit when EOF is reached and all but the top-level scope is
  797. /// popped.
  798. void Sema::ActOnEndOfTranslationUnit() {
  799. assert(DelayedDiagnostics.getCurrentPool() == nullptr
  800. && "reached end of translation unit with a pool attached?");
  801. // If code completion is enabled, don't perform any end-of-translation-unit
  802. // work.
  803. if (PP.isCodeCompletionEnabled())
  804. return;
  805. // Complete translation units and modules define vtables and perform implicit
  806. // instantiations. PCH files do not.
  807. if (TUKind != TU_Prefix) {
  808. DiagnoseUseOfUnimplementedSelectors();
  809. ActOnEndOfTranslationUnitFragment(
  810. !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
  811. Module::PrivateModuleFragment
  812. ? TUFragmentKind::Private
  813. : TUFragmentKind::Normal);
  814. if (LateTemplateParserCleanup)
  815. LateTemplateParserCleanup(OpaqueParser);
  816. CheckDelayedMemberExceptionSpecs();
  817. } else {
  818. // If we are building a TU prefix for serialization, it is safe to transfer
  819. // these over, even though they are not parsed. The end of the TU should be
  820. // outside of any eager template instantiation scope, so when this AST is
  821. // deserialized, these templates will not be parsed until the end of the
  822. // combined TU.
  823. PendingInstantiations.insert(PendingInstantiations.end(),
  824. LateParsedInstantiations.begin(),
  825. LateParsedInstantiations.end());
  826. LateParsedInstantiations.clear();
  827. }
  828. DiagnoseUnterminatedPragmaPack();
  829. DiagnoseUnterminatedPragmaAttribute();
  830. // All delayed member exception specs should be checked or we end up accepting
  831. // incompatible declarations.
  832. assert(DelayedOverridingExceptionSpecChecks.empty());
  833. assert(DelayedEquivalentExceptionSpecChecks.empty());
  834. // All dllexport classes should have been processed already.
  835. assert(DelayedDllExportClasses.empty());
  836. // Remove file scoped decls that turned out to be used.
  837. UnusedFileScopedDecls.erase(
  838. std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
  839. UnusedFileScopedDecls.end(),
  840. [this](const DeclaratorDecl *DD) {
  841. return ShouldRemoveFromUnused(this, DD);
  842. }),
  843. UnusedFileScopedDecls.end());
  844. if (TUKind == TU_Prefix) {
  845. // Translation unit prefixes don't need any of the checking below.
  846. if (!PP.isIncrementalProcessingEnabled())
  847. TUScope = nullptr;
  848. return;
  849. }
  850. // Check for #pragma weak identifiers that were never declared
  851. LoadExternalWeakUndeclaredIdentifiers();
  852. for (auto WeakID : WeakUndeclaredIdentifiers) {
  853. if (WeakID.second.getUsed())
  854. continue;
  855. Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
  856. LookupOrdinaryName);
  857. if (PrevDecl != nullptr &&
  858. !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
  859. Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
  860. << "'weak'" << ExpectedVariableOrFunction;
  861. else
  862. Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
  863. << WeakID.first;
  864. }
  865. if (LangOpts.CPlusPlus11 &&
  866. !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
  867. CheckDelegatingCtorCycles();
  868. if (!Diags.hasErrorOccurred()) {
  869. if (ExternalSource)
  870. ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
  871. checkUndefinedButUsed(*this);
  872. }
  873. // A global-module-fragment is only permitted within a module unit.
  874. bool DiagnosedMissingModuleDeclaration = false;
  875. if (!ModuleScopes.empty() &&
  876. ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
  877. !ModuleScopes.back().ImplicitGlobalModuleFragment) {
  878. Diag(ModuleScopes.back().BeginLoc,
  879. diag::err_module_declaration_missing_after_global_module_introducer);
  880. DiagnosedMissingModuleDeclaration = true;
  881. }
  882. if (TUKind == TU_Module) {
  883. // If we are building a module interface unit, we need to have seen the
  884. // module declaration by now.
  885. if (getLangOpts().getCompilingModule() ==
  886. LangOptions::CMK_ModuleInterface &&
  887. (ModuleScopes.empty() ||
  888. !ModuleScopes.back().Module->isModulePurview()) &&
  889. !DiagnosedMissingModuleDeclaration) {
  890. // FIXME: Make a better guess as to where to put the module declaration.
  891. Diag(getSourceManager().getLocForStartOfFile(
  892. getSourceManager().getMainFileID()),
  893. diag::err_module_declaration_missing);
  894. }
  895. // If we are building a module, resolve all of the exported declarations
  896. // now.
  897. if (Module *CurrentModule = PP.getCurrentModule()) {
  898. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  899. SmallVector<Module *, 2> Stack;
  900. Stack.push_back(CurrentModule);
  901. while (!Stack.empty()) {
  902. Module *Mod = Stack.pop_back_val();
  903. // Resolve the exported declarations and conflicts.
  904. // FIXME: Actually complain, once we figure out how to teach the
  905. // diagnostic client to deal with complaints in the module map at this
  906. // point.
  907. ModMap.resolveExports(Mod, /*Complain=*/false);
  908. ModMap.resolveUses(Mod, /*Complain=*/false);
  909. ModMap.resolveConflicts(Mod, /*Complain=*/false);
  910. // Queue the submodules, so their exports will also be resolved.
  911. Stack.append(Mod->submodule_begin(), Mod->submodule_end());
  912. }
  913. }
  914. // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
  915. // modules when they are built, not every time they are used.
  916. emitAndClearUnusedLocalTypedefWarnings();
  917. }
  918. // C99 6.9.2p2:
  919. // A declaration of an identifier for an object that has file
  920. // scope without an initializer, and without a storage-class
  921. // specifier or with the storage-class specifier static,
  922. // constitutes a tentative definition. If a translation unit
  923. // contains one or more tentative definitions for an identifier,
  924. // and the translation unit contains no external definition for
  925. // that identifier, then the behavior is exactly as if the
  926. // translation unit contains a file scope declaration of that
  927. // identifier, with the composite type as of the end of the
  928. // translation unit, with an initializer equal to 0.
  929. llvm::SmallSet<VarDecl *, 32> Seen;
  930. for (TentativeDefinitionsType::iterator
  931. T = TentativeDefinitions.begin(ExternalSource),
  932. TEnd = TentativeDefinitions.end();
  933. T != TEnd; ++T) {
  934. VarDecl *VD = (*T)->getActingDefinition();
  935. // If the tentative definition was completed, getActingDefinition() returns
  936. // null. If we've already seen this variable before, insert()'s second
  937. // return value is false.
  938. if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
  939. continue;
  940. if (const IncompleteArrayType *ArrayT
  941. = Context.getAsIncompleteArrayType(VD->getType())) {
  942. // Set the length of the array to 1 (C99 6.9.2p5).
  943. Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
  944. llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
  945. QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
  946. One, ArrayType::Normal, 0);
  947. VD->setType(T);
  948. } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
  949. diag::err_tentative_def_incomplete_type))
  950. VD->setInvalidDecl();
  951. // No initialization is performed for a tentative definition.
  952. CheckCompleteVariableDeclaration(VD);
  953. // Notify the consumer that we've completed a tentative definition.
  954. if (!VD->isInvalidDecl())
  955. Consumer.CompleteTentativeDefinition(VD);
  956. }
  957. // If there were errors, disable 'unused' warnings since they will mostly be
  958. // noise. Don't warn for a use from a module: either we should warn on all
  959. // file-scope declarations in modules or not at all, but whether the
  960. // declaration is used is immaterial.
  961. if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
  962. // Output warning for unused file scoped decls.
  963. for (UnusedFileScopedDeclsType::iterator
  964. I = UnusedFileScopedDecls.begin(ExternalSource),
  965. E = UnusedFileScopedDecls.end(); I != E; ++I) {
  966. if (ShouldRemoveFromUnused(this, *I))
  967. continue;
  968. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  969. const FunctionDecl *DiagD;
  970. if (!FD->hasBody(DiagD))
  971. DiagD = FD;
  972. if (DiagD->isDeleted())
  973. continue; // Deleted functions are supposed to be unused.
  974. if (DiagD->isReferenced()) {
  975. if (isa<CXXMethodDecl>(DiagD))
  976. Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
  977. << DiagD->getDeclName();
  978. else {
  979. if (FD->getStorageClass() == SC_Static &&
  980. !FD->isInlineSpecified() &&
  981. !SourceMgr.isInMainFile(
  982. SourceMgr.getExpansionLoc(FD->getLocation())))
  983. Diag(DiagD->getLocation(),
  984. diag::warn_unneeded_static_internal_decl)
  985. << DiagD->getDeclName();
  986. else
  987. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  988. << /*function*/0 << DiagD->getDeclName();
  989. }
  990. } else {
  991. if (FD->getDescribedFunctionTemplate())
  992. Diag(DiagD->getLocation(), diag::warn_unused_template)
  993. << /*function*/0 << DiagD->getDeclName();
  994. else
  995. Diag(DiagD->getLocation(),
  996. isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
  997. : diag::warn_unused_function)
  998. << DiagD->getDeclName();
  999. }
  1000. } else {
  1001. const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
  1002. if (!DiagD)
  1003. DiagD = cast<VarDecl>(*I);
  1004. if (DiagD->isReferenced()) {
  1005. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  1006. << /*variable*/1 << DiagD->getDeclName();
  1007. } else if (DiagD->getType().isConstQualified()) {
  1008. const SourceManager &SM = SourceMgr;
  1009. if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
  1010. !PP.getLangOpts().IsHeaderFile)
  1011. Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
  1012. << DiagD->getDeclName();
  1013. } else {
  1014. if (DiagD->getDescribedVarTemplate())
  1015. Diag(DiagD->getLocation(), diag::warn_unused_template)
  1016. << /*variable*/1 << DiagD->getDeclName();
  1017. else
  1018. Diag(DiagD->getLocation(), diag::warn_unused_variable)
  1019. << DiagD->getDeclName();
  1020. }
  1021. }
  1022. }
  1023. emitAndClearUnusedLocalTypedefWarnings();
  1024. }
  1025. if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
  1026. // FIXME: Load additional unused private field candidates from the external
  1027. // source.
  1028. RecordCompleteMap RecordsComplete;
  1029. RecordCompleteMap MNCComplete;
  1030. for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
  1031. E = UnusedPrivateFields.end(); I != E; ++I) {
  1032. const NamedDecl *D = *I;
  1033. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  1034. if (RD && !RD->isUnion() &&
  1035. IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
  1036. Diag(D->getLocation(), diag::warn_unused_private_field)
  1037. << D->getDeclName();
  1038. }
  1039. }
  1040. }
  1041. if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
  1042. if (ExternalSource)
  1043. ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
  1044. for (const auto &DeletedFieldInfo : DeleteExprs) {
  1045. for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
  1046. AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
  1047. DeleteExprLoc.second);
  1048. }
  1049. }
  1050. }
  1051. // Check we've noticed that we're no longer parsing the initializer for every
  1052. // variable. If we miss cases, then at best we have a performance issue and
  1053. // at worst a rejects-valid bug.
  1054. assert(ParsingInitForAutoVars.empty() &&
  1055. "Didn't unmark var as having its initializer parsed");
  1056. if (!PP.isIncrementalProcessingEnabled())
  1057. TUScope = nullptr;
  1058. }
  1059. //===----------------------------------------------------------------------===//
  1060. // Helper functions.
  1061. //===----------------------------------------------------------------------===//
  1062. DeclContext *Sema::getFunctionLevelDeclContext() {
  1063. DeclContext *DC = CurContext;
  1064. while (true) {
  1065. if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
  1066. DC = DC->getParent();
  1067. } else if (isa<CXXMethodDecl>(DC) &&
  1068. cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
  1069. cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
  1070. DC = DC->getParent()->getParent();
  1071. }
  1072. else break;
  1073. }
  1074. return DC;
  1075. }
  1076. /// getCurFunctionDecl - If inside of a function body, this returns a pointer
  1077. /// to the function decl for the function being parsed. If we're currently
  1078. /// in a 'block', this returns the containing context.
  1079. FunctionDecl *Sema::getCurFunctionDecl() {
  1080. DeclContext *DC = getFunctionLevelDeclContext();
  1081. return dyn_cast<FunctionDecl>(DC);
  1082. }
  1083. ObjCMethodDecl *Sema::getCurMethodDecl() {
  1084. DeclContext *DC = getFunctionLevelDeclContext();
  1085. while (isa<RecordDecl>(DC))
  1086. DC = DC->getParent();
  1087. return dyn_cast<ObjCMethodDecl>(DC);
  1088. }
  1089. NamedDecl *Sema::getCurFunctionOrMethodDecl() {
  1090. DeclContext *DC = getFunctionLevelDeclContext();
  1091. if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
  1092. return cast<NamedDecl>(DC);
  1093. return nullptr;
  1094. }
  1095. void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
  1096. // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
  1097. // and yet we also use the current diag ID on the DiagnosticsEngine. This has
  1098. // been made more painfully obvious by the refactor that introduced this
  1099. // function, but it is possible that the incoming argument can be
  1100. // eliminated. If it truly cannot be (for example, there is some reentrancy
  1101. // issue I am not seeing yet), then there should at least be a clarifying
  1102. // comment somewhere.
  1103. if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
  1104. switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
  1105. Diags.getCurrentDiagID())) {
  1106. case DiagnosticIDs::SFINAE_Report:
  1107. // We'll report the diagnostic below.
  1108. break;
  1109. case DiagnosticIDs::SFINAE_SubstitutionFailure:
  1110. // Count this failure so that we know that template argument deduction
  1111. // has failed.
  1112. ++NumSFINAEErrors;
  1113. // Make a copy of this suppressed diagnostic and store it with the
  1114. // template-deduction information.
  1115. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1116. Diagnostic DiagInfo(&Diags);
  1117. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1118. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1119. }
  1120. Diags.setLastDiagnosticIgnored();
  1121. Diags.Clear();
  1122. return;
  1123. case DiagnosticIDs::SFINAE_AccessControl: {
  1124. // Per C++ Core Issue 1170, access control is part of SFINAE.
  1125. // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
  1126. // make access control a part of SFINAE for the purposes of checking
  1127. // type traits.
  1128. if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
  1129. break;
  1130. SourceLocation Loc = Diags.getCurrentDiagLoc();
  1131. // Suppress this diagnostic.
  1132. ++NumSFINAEErrors;
  1133. // Make a copy of this suppressed diagnostic and store it with the
  1134. // template-deduction information.
  1135. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1136. Diagnostic DiagInfo(&Diags);
  1137. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1138. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1139. }
  1140. Diags.setLastDiagnosticIgnored();
  1141. Diags.Clear();
  1142. // Now the diagnostic state is clear, produce a C++98 compatibility
  1143. // warning.
  1144. Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
  1145. // The last diagnostic which Sema produced was ignored. Suppress any
  1146. // notes attached to it.
  1147. Diags.setLastDiagnosticIgnored();
  1148. return;
  1149. }
  1150. case DiagnosticIDs::SFINAE_Suppress:
  1151. // Make a copy of this suppressed diagnostic and store it with the
  1152. // template-deduction information;
  1153. if (*Info) {
  1154. Diagnostic DiagInfo(&Diags);
  1155. (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
  1156. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1157. }
  1158. // Suppress this diagnostic.
  1159. Diags.setLastDiagnosticIgnored();
  1160. Diags.Clear();
  1161. return;
  1162. }
  1163. }
  1164. // Copy the diagnostic printing policy over the ASTContext printing policy.
  1165. // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
  1166. Context.setPrintingPolicy(getPrintingPolicy());
  1167. // Emit the diagnostic.
  1168. if (!Diags.EmitCurrentDiagnostic())
  1169. return;
  1170. // If this is not a note, and we're in a template instantiation
  1171. // that is different from the last template instantiation where
  1172. // we emitted an error, print a template instantiation
  1173. // backtrace.
  1174. if (!DiagnosticIDs::isBuiltinNote(DiagID))
  1175. PrintContextStack();
  1176. }
  1177. Sema::SemaDiagnosticBuilder
  1178. Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
  1179. SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
  1180. PD.Emit(Builder);
  1181. return Builder;
  1182. }
  1183. // Print notes showing how we can reach FD starting from an a priori
  1184. // known-callable function.
  1185. static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
  1186. auto FnIt = S.DeviceKnownEmittedFns.find(FD);
  1187. while (FnIt != S.DeviceKnownEmittedFns.end()) {
  1188. DiagnosticBuilder Builder(
  1189. S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
  1190. Builder << FnIt->second.FD;
  1191. Builder.setForceEmit();
  1192. FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
  1193. }
  1194. }
  1195. // Emit any deferred diagnostics for FD and erase them from the map in which
  1196. // they're stored.
  1197. static void emitDeferredDiags(Sema &S, FunctionDecl *FD) {
  1198. auto It = S.DeviceDeferredDiags.find(FD);
  1199. if (It == S.DeviceDeferredDiags.end())
  1200. return;
  1201. bool HasWarningOrError = false;
  1202. for (PartialDiagnosticAt &PDAt : It->second) {
  1203. const SourceLocation &Loc = PDAt.first;
  1204. const PartialDiagnostic &PD = PDAt.second;
  1205. HasWarningOrError |= S.getDiagnostics().getDiagnosticLevel(
  1206. PD.getDiagID(), Loc) >= DiagnosticsEngine::Warning;
  1207. DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
  1208. Builder.setForceEmit();
  1209. PD.Emit(Builder);
  1210. }
  1211. S.DeviceDeferredDiags.erase(It);
  1212. // FIXME: Should this be called after every warning/error emitted in the loop
  1213. // above, instead of just once per function? That would be consistent with
  1214. // how we handle immediate errors, but it also seems like a bit much.
  1215. if (HasWarningOrError)
  1216. emitCallStackNotes(S, FD);
  1217. }
  1218. // In CUDA, there are some constructs which may appear in semantically-valid
  1219. // code, but trigger errors if we ever generate code for the function in which
  1220. // they appear. Essentially every construct you're not allowed to use on the
  1221. // device falls into this category, because you are allowed to use these
  1222. // constructs in a __host__ __device__ function, but only if that function is
  1223. // never codegen'ed on the device.
  1224. //
  1225. // To handle semantic checking for these constructs, we keep track of the set of
  1226. // functions we know will be emitted, either because we could tell a priori that
  1227. // they would be emitted, or because they were transitively called by a
  1228. // known-emitted function.
  1229. //
  1230. // We also keep a partial call graph of which not-known-emitted functions call
  1231. // which other not-known-emitted functions.
  1232. //
  1233. // When we see something which is illegal if the current function is emitted
  1234. // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
  1235. // CheckCUDACall), we first check if the current function is known-emitted. If
  1236. // so, we immediately output the diagnostic.
  1237. //
  1238. // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
  1239. // until we discover that the function is known-emitted, at which point we take
  1240. // it out of this map and emit the diagnostic.
  1241. Sema::DeviceDiagBuilder::DeviceDiagBuilder(Kind K, SourceLocation Loc,
  1242. unsigned DiagID, FunctionDecl *Fn,
  1243. Sema &S)
  1244. : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
  1245. ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
  1246. switch (K) {
  1247. case K_Nop:
  1248. break;
  1249. case K_Immediate:
  1250. case K_ImmediateWithCallStack:
  1251. ImmediateDiag.emplace(S.Diag(Loc, DiagID));
  1252. break;
  1253. case K_Deferred:
  1254. assert(Fn && "Must have a function to attach the deferred diag to.");
  1255. auto &Diags = S.DeviceDeferredDiags[Fn];
  1256. PartialDiagId.emplace(Diags.size());
  1257. Diags.emplace_back(Loc, S.PDiag(DiagID));
  1258. break;
  1259. }
  1260. }
  1261. Sema::DeviceDiagBuilder::DeviceDiagBuilder(DeviceDiagBuilder &&D)
  1262. : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
  1263. ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
  1264. PartialDiagId(D.PartialDiagId) {
  1265. // Clean the previous diagnostics.
  1266. D.ShowCallStack = false;
  1267. D.ImmediateDiag.reset();
  1268. D.PartialDiagId.reset();
  1269. }
  1270. Sema::DeviceDiagBuilder::~DeviceDiagBuilder() {
  1271. if (ImmediateDiag) {
  1272. // Emit our diagnostic and, if it was a warning or error, output a callstack
  1273. // if Fn isn't a priori known-emitted.
  1274. bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
  1275. DiagID, Loc) >= DiagnosticsEngine::Warning;
  1276. ImmediateDiag.reset(); // Emit the immediate diag.
  1277. if (IsWarningOrError && ShowCallStack)
  1278. emitCallStackNotes(S, Fn);
  1279. } else {
  1280. assert((!PartialDiagId || ShowCallStack) &&
  1281. "Must always show call stack for deferred diags.");
  1282. }
  1283. }
  1284. // Indicate that this function (and thus everything it transtively calls) will
  1285. // be codegen'ed, and emit any deferred diagnostics on this function and its
  1286. // (transitive) callees.
  1287. void Sema::markKnownEmitted(
  1288. Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
  1289. SourceLocation OrigLoc,
  1290. const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted) {
  1291. // Nothing to do if we already know that FD is emitted.
  1292. if (IsKnownEmitted(S, OrigCallee)) {
  1293. assert(!S.DeviceCallGraph.count(OrigCallee));
  1294. return;
  1295. }
  1296. // We've just discovered that OrigCallee is known-emitted. Walk our call
  1297. // graph to see what else we can now discover also must be emitted.
  1298. struct CallInfo {
  1299. FunctionDecl *Caller;
  1300. FunctionDecl *Callee;
  1301. SourceLocation Loc;
  1302. };
  1303. llvm::SmallVector<CallInfo, 4> Worklist = {{OrigCaller, OrigCallee, OrigLoc}};
  1304. llvm::SmallSet<CanonicalDeclPtr<FunctionDecl>, 4> Seen;
  1305. Seen.insert(OrigCallee);
  1306. while (!Worklist.empty()) {
  1307. CallInfo C = Worklist.pop_back_val();
  1308. assert(!IsKnownEmitted(S, C.Callee) &&
  1309. "Worklist should not contain known-emitted functions.");
  1310. S.DeviceKnownEmittedFns[C.Callee] = {C.Caller, C.Loc};
  1311. emitDeferredDiags(S, C.Callee);
  1312. // If this is a template instantiation, explore its callgraph as well:
  1313. // Non-dependent calls are part of the template's callgraph, while dependent
  1314. // calls are part of to the instantiation's call graph.
  1315. if (auto *Templ = C.Callee->getPrimaryTemplate()) {
  1316. FunctionDecl *TemplFD = Templ->getAsFunction();
  1317. if (!Seen.count(TemplFD) && !S.DeviceKnownEmittedFns.count(TemplFD)) {
  1318. Seen.insert(TemplFD);
  1319. Worklist.push_back(
  1320. {/* Caller = */ C.Caller, /* Callee = */ TemplFD, C.Loc});
  1321. }
  1322. }
  1323. // Add all functions called by Callee to our worklist.
  1324. auto CGIt = S.DeviceCallGraph.find(C.Callee);
  1325. if (CGIt == S.DeviceCallGraph.end())
  1326. continue;
  1327. for (std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation> FDLoc :
  1328. CGIt->second) {
  1329. FunctionDecl *NewCallee = FDLoc.first;
  1330. SourceLocation CallLoc = FDLoc.second;
  1331. if (Seen.count(NewCallee) || IsKnownEmitted(S, NewCallee))
  1332. continue;
  1333. Seen.insert(NewCallee);
  1334. Worklist.push_back(
  1335. {/* Caller = */ C.Callee, /* Callee = */ NewCallee, CallLoc});
  1336. }
  1337. // C.Callee is now known-emitted, so we no longer need to maintain its list
  1338. // of callees in DeviceCallGraph.
  1339. S.DeviceCallGraph.erase(CGIt);
  1340. }
  1341. }
  1342. Sema::DeviceDiagBuilder Sema::targetDiag(SourceLocation Loc, unsigned DiagID) {
  1343. if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
  1344. return diagIfOpenMPDeviceCode(Loc, DiagID);
  1345. if (getLangOpts().CUDA)
  1346. return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
  1347. : CUDADiagIfHostCode(Loc, DiagID);
  1348. return DeviceDiagBuilder(DeviceDiagBuilder::K_Immediate, Loc, DiagID,
  1349. getCurFunctionDecl(), *this);
  1350. }
  1351. /// Looks through the macro-expansion chain for the given
  1352. /// location, looking for a macro expansion with the given name.
  1353. /// If one is found, returns true and sets the location to that
  1354. /// expansion loc.
  1355. bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
  1356. SourceLocation loc = locref;
  1357. if (!loc.isMacroID()) return false;
  1358. // There's no good way right now to look at the intermediate
  1359. // expansions, so just jump to the expansion location.
  1360. loc = getSourceManager().getExpansionLoc(loc);
  1361. // If that's written with the name, stop here.
  1362. SmallVector<char, 16> buffer;
  1363. if (getPreprocessor().getSpelling(loc, buffer) == name) {
  1364. locref = loc;
  1365. return true;
  1366. }
  1367. return false;
  1368. }
  1369. /// Determines the active Scope associated with the given declaration
  1370. /// context.
  1371. ///
  1372. /// This routine maps a declaration context to the active Scope object that
  1373. /// represents that declaration context in the parser. It is typically used
  1374. /// from "scope-less" code (e.g., template instantiation, lazy creation of
  1375. /// declarations) that injects a name for name-lookup purposes and, therefore,
  1376. /// must update the Scope.
  1377. ///
  1378. /// \returns The scope corresponding to the given declaraion context, or NULL
  1379. /// if no such scope is open.
  1380. Scope *Sema::getScopeForContext(DeclContext *Ctx) {
  1381. if (!Ctx)
  1382. return nullptr;
  1383. Ctx = Ctx->getPrimaryContext();
  1384. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1385. // Ignore scopes that cannot have declarations. This is important for
  1386. // out-of-line definitions of static class members.
  1387. if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
  1388. if (DeclContext *Entity = S->getEntity())
  1389. if (Ctx == Entity->getPrimaryContext())
  1390. return S;
  1391. }
  1392. return nullptr;
  1393. }
  1394. /// Enter a new function scope
  1395. void Sema::PushFunctionScope() {
  1396. if (FunctionScopes.empty() && CachedFunctionScope) {
  1397. // Use CachedFunctionScope to avoid allocating memory when possible.
  1398. CachedFunctionScope->Clear();
  1399. FunctionScopes.push_back(CachedFunctionScope.release());
  1400. } else {
  1401. FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
  1402. }
  1403. if (LangOpts.OpenMP)
  1404. pushOpenMPFunctionRegion();
  1405. }
  1406. void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
  1407. FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
  1408. BlockScope, Block));
  1409. }
  1410. LambdaScopeInfo *Sema::PushLambdaScope() {
  1411. LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
  1412. FunctionScopes.push_back(LSI);
  1413. return LSI;
  1414. }
  1415. void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
  1416. if (LambdaScopeInfo *const LSI = getCurLambda()) {
  1417. LSI->AutoTemplateParameterDepth = Depth;
  1418. return;
  1419. }
  1420. llvm_unreachable(
  1421. "Remove assertion if intentionally called in a non-lambda context.");
  1422. }
  1423. // Check that the type of the VarDecl has an accessible copy constructor and
  1424. // resolve its destructor's exception specification.
  1425. static void checkEscapingByref(VarDecl *VD, Sema &S) {
  1426. QualType T = VD->getType();
  1427. EnterExpressionEvaluationContext scope(
  1428. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  1429. SourceLocation Loc = VD->getLocation();
  1430. Expr *VarRef =
  1431. new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
  1432. ExprResult Result = S.PerformMoveOrCopyInitialization(
  1433. InitializedEntity::InitializeBlock(Loc, T, false), VD, VD->getType(),
  1434. VarRef, /*AllowNRVO=*/true);
  1435. if (!Result.isInvalid()) {
  1436. Result = S.MaybeCreateExprWithCleanups(Result);
  1437. Expr *Init = Result.getAs<Expr>();
  1438. S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
  1439. }
  1440. // The destructor's exception specification is needed when IRGen generates
  1441. // block copy/destroy functions. Resolve it here.
  1442. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  1443. if (CXXDestructorDecl *DD = RD->getDestructor()) {
  1444. auto *FPT = DD->getType()->getAs<FunctionProtoType>();
  1445. S.ResolveExceptionSpec(Loc, FPT);
  1446. }
  1447. }
  1448. static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
  1449. // Set the EscapingByref flag of __block variables captured by
  1450. // escaping blocks.
  1451. for (const BlockDecl *BD : FSI.Blocks) {
  1452. for (const BlockDecl::Capture &BC : BD->captures()) {
  1453. VarDecl *VD = BC.getVariable();
  1454. if (VD->hasAttr<BlocksAttr>()) {
  1455. // Nothing to do if this is a __block variable captured by a
  1456. // non-escaping block.
  1457. if (BD->doesNotEscape())
  1458. continue;
  1459. VD->setEscapingByref();
  1460. }
  1461. // Check whether the captured variable is or contains an object of
  1462. // non-trivial C union type.
  1463. QualType CapType = BC.getVariable()->getType();
  1464. if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
  1465. CapType.hasNonTrivialToPrimitiveCopyCUnion())
  1466. S.checkNonTrivialCUnion(BC.getVariable()->getType(),
  1467. BD->getCaretLocation(),
  1468. Sema::NTCUC_BlockCapture,
  1469. Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
  1470. }
  1471. }
  1472. for (VarDecl *VD : FSI.ByrefBlockVars) {
  1473. // __block variables might require us to capture a copy-initializer.
  1474. if (!VD->isEscapingByref())
  1475. continue;
  1476. // It's currently invalid to ever have a __block variable with an
  1477. // array type; should we diagnose that here?
  1478. // Regardless, we don't want to ignore array nesting when
  1479. // constructing this copy.
  1480. if (VD->getType()->isStructureOrClassType())
  1481. checkEscapingByref(VD, S);
  1482. }
  1483. }
  1484. /// Pop a function (or block or lambda or captured region) scope from the stack.
  1485. ///
  1486. /// \param WP The warning policy to use for CFG-based warnings, or null if such
  1487. /// warnings should not be produced.
  1488. /// \param D The declaration corresponding to this function scope, if producing
  1489. /// CFG-based warnings.
  1490. /// \param BlockType The type of the block expression, if D is a BlockDecl.
  1491. Sema::PoppedFunctionScopePtr
  1492. Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
  1493. const Decl *D, QualType BlockType) {
  1494. assert(!FunctionScopes.empty() && "mismatched push/pop!");
  1495. markEscapingByrefs(*FunctionScopes.back(), *this);
  1496. PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
  1497. PoppedFunctionScopeDeleter(this));
  1498. if (LangOpts.OpenMP)
  1499. popOpenMPFunctionRegion(Scope.get());
  1500. // Issue any analysis-based warnings.
  1501. if (WP && D)
  1502. AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
  1503. else
  1504. for (const auto &PUD : Scope->PossiblyUnreachableDiags)
  1505. Diag(PUD.Loc, PUD.PD);
  1506. return Scope;
  1507. }
  1508. void Sema::PoppedFunctionScopeDeleter::
  1509. operator()(sema::FunctionScopeInfo *Scope) const {
  1510. // Stash the function scope for later reuse if it's for a normal function.
  1511. if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
  1512. Self->CachedFunctionScope.reset(Scope);
  1513. else
  1514. delete Scope;
  1515. }
  1516. void Sema::PushCompoundScope(bool IsStmtExpr) {
  1517. getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
  1518. }
  1519. void Sema::PopCompoundScope() {
  1520. FunctionScopeInfo *CurFunction = getCurFunction();
  1521. assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
  1522. CurFunction->CompoundScopes.pop_back();
  1523. }
  1524. /// Determine whether any errors occurred within this function/method/
  1525. /// block.
  1526. bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
  1527. return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
  1528. }
  1529. void Sema::setFunctionHasBranchIntoScope() {
  1530. if (!FunctionScopes.empty())
  1531. FunctionScopes.back()->setHasBranchIntoScope();
  1532. }
  1533. void Sema::setFunctionHasBranchProtectedScope() {
  1534. if (!FunctionScopes.empty())
  1535. FunctionScopes.back()->setHasBranchProtectedScope();
  1536. }
  1537. void Sema::setFunctionHasIndirectGoto() {
  1538. if (!FunctionScopes.empty())
  1539. FunctionScopes.back()->setHasIndirectGoto();
  1540. }
  1541. BlockScopeInfo *Sema::getCurBlock() {
  1542. if (FunctionScopes.empty())
  1543. return nullptr;
  1544. auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
  1545. if (CurBSI && CurBSI->TheDecl &&
  1546. !CurBSI->TheDecl->Encloses(CurContext)) {
  1547. // We have switched contexts due to template instantiation.
  1548. assert(!CodeSynthesisContexts.empty());
  1549. return nullptr;
  1550. }
  1551. return CurBSI;
  1552. }
  1553. FunctionScopeInfo *Sema::getEnclosingFunction() const {
  1554. if (FunctionScopes.empty())
  1555. return nullptr;
  1556. for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
  1557. if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
  1558. continue;
  1559. return FunctionScopes[e];
  1560. }
  1561. return nullptr;
  1562. }
  1563. LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
  1564. if (FunctionScopes.empty())
  1565. return nullptr;
  1566. auto I = FunctionScopes.rbegin();
  1567. if (IgnoreNonLambdaCapturingScope) {
  1568. auto E = FunctionScopes.rend();
  1569. while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
  1570. ++I;
  1571. if (I == E)
  1572. return nullptr;
  1573. }
  1574. auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
  1575. if (CurLSI && CurLSI->Lambda &&
  1576. !CurLSI->Lambda->Encloses(CurContext)) {
  1577. // We have switched contexts due to template instantiation.
  1578. assert(!CodeSynthesisContexts.empty());
  1579. return nullptr;
  1580. }
  1581. return CurLSI;
  1582. }
  1583. // We have a generic lambda if we parsed auto parameters, or we have
  1584. // an associated template parameter list.
  1585. LambdaScopeInfo *Sema::getCurGenericLambda() {
  1586. if (LambdaScopeInfo *LSI = getCurLambda()) {
  1587. return (LSI->TemplateParams.size() ||
  1588. LSI->GLTemplateParameterList) ? LSI : nullptr;
  1589. }
  1590. return nullptr;
  1591. }
  1592. void Sema::ActOnComment(SourceRange Comment) {
  1593. if (!LangOpts.RetainCommentsFromSystemHeaders &&
  1594. SourceMgr.isInSystemHeader(Comment.getBegin()))
  1595. return;
  1596. RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
  1597. if (RC.isAlmostTrailingComment()) {
  1598. SourceRange MagicMarkerRange(Comment.getBegin(),
  1599. Comment.getBegin().getLocWithOffset(3));
  1600. StringRef MagicMarkerText;
  1601. switch (RC.getKind()) {
  1602. case RawComment::RCK_OrdinaryBCPL:
  1603. MagicMarkerText = "///<";
  1604. break;
  1605. case RawComment::RCK_OrdinaryC:
  1606. MagicMarkerText = "/**<";
  1607. break;
  1608. default:
  1609. llvm_unreachable("if this is an almost Doxygen comment, "
  1610. "it should be ordinary");
  1611. }
  1612. Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
  1613. FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
  1614. }
  1615. Context.addComment(RC);
  1616. }
  1617. // Pin this vtable to this file.
  1618. ExternalSemaSource::~ExternalSemaSource() {}
  1619. void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
  1620. void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
  1621. void ExternalSemaSource::ReadKnownNamespaces(
  1622. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  1623. }
  1624. void ExternalSemaSource::ReadUndefinedButUsed(
  1625. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
  1626. void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
  1627. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
  1628. /// Figure out if an expression could be turned into a call.
  1629. ///
  1630. /// Use this when trying to recover from an error where the programmer may have
  1631. /// written just the name of a function instead of actually calling it.
  1632. ///
  1633. /// \param E - The expression to examine.
  1634. /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
  1635. /// with no arguments, this parameter is set to the type returned by such a
  1636. /// call; otherwise, it is set to an empty QualType.
  1637. /// \param OverloadSet - If the expression is an overloaded function
  1638. /// name, this parameter is populated with the decls of the various overloads.
  1639. bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
  1640. UnresolvedSetImpl &OverloadSet) {
  1641. ZeroArgCallReturnTy = QualType();
  1642. OverloadSet.clear();
  1643. const OverloadExpr *Overloads = nullptr;
  1644. bool IsMemExpr = false;
  1645. if (E.getType() == Context.OverloadTy) {
  1646. OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
  1647. // Ignore overloads that are pointer-to-member constants.
  1648. if (FR.HasFormOfMemberPointer)
  1649. return false;
  1650. Overloads = FR.Expression;
  1651. } else if (E.getType() == Context.BoundMemberTy) {
  1652. Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
  1653. IsMemExpr = true;
  1654. }
  1655. bool Ambiguous = false;
  1656. bool IsMV = false;
  1657. if (Overloads) {
  1658. for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
  1659. DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
  1660. OverloadSet.addDecl(*it);
  1661. // Check whether the function is a non-template, non-member which takes no
  1662. // arguments.
  1663. if (IsMemExpr)
  1664. continue;
  1665. if (const FunctionDecl *OverloadDecl
  1666. = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
  1667. if (OverloadDecl->getMinRequiredArguments() == 0) {
  1668. if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
  1669. (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
  1670. OverloadDecl->isCPUSpecificMultiVersion()))) {
  1671. ZeroArgCallReturnTy = QualType();
  1672. Ambiguous = true;
  1673. } else {
  1674. ZeroArgCallReturnTy = OverloadDecl->getReturnType();
  1675. IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
  1676. OverloadDecl->isCPUSpecificMultiVersion();
  1677. }
  1678. }
  1679. }
  1680. }
  1681. // If it's not a member, use better machinery to try to resolve the call
  1682. if (!IsMemExpr)
  1683. return !ZeroArgCallReturnTy.isNull();
  1684. }
  1685. // Attempt to call the member with no arguments - this will correctly handle
  1686. // member templates with defaults/deduction of template arguments, overloads
  1687. // with default arguments, etc.
  1688. if (IsMemExpr && !E.isTypeDependent()) {
  1689. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  1690. getDiagnostics().setSuppressAllDiagnostics(true);
  1691. ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
  1692. None, SourceLocation());
  1693. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  1694. if (R.isUsable()) {
  1695. ZeroArgCallReturnTy = R.get()->getType();
  1696. return true;
  1697. }
  1698. return false;
  1699. }
  1700. if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
  1701. if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
  1702. if (Fun->getMinRequiredArguments() == 0)
  1703. ZeroArgCallReturnTy = Fun->getReturnType();
  1704. return true;
  1705. }
  1706. }
  1707. // We don't have an expression that's convenient to get a FunctionDecl from,
  1708. // but we can at least check if the type is "function of 0 arguments".
  1709. QualType ExprTy = E.getType();
  1710. const FunctionType *FunTy = nullptr;
  1711. QualType PointeeTy = ExprTy->getPointeeType();
  1712. if (!PointeeTy.isNull())
  1713. FunTy = PointeeTy->getAs<FunctionType>();
  1714. if (!FunTy)
  1715. FunTy = ExprTy->getAs<FunctionType>();
  1716. if (const FunctionProtoType *FPT =
  1717. dyn_cast_or_null<FunctionProtoType>(FunTy)) {
  1718. if (FPT->getNumParams() == 0)
  1719. ZeroArgCallReturnTy = FunTy->getReturnType();
  1720. return true;
  1721. }
  1722. return false;
  1723. }
  1724. /// Give notes for a set of overloads.
  1725. ///
  1726. /// A companion to tryExprAsCall. In cases when the name that the programmer
  1727. /// wrote was an overloaded function, we may be able to make some guesses about
  1728. /// plausible overloads based on their return types; such guesses can be handed
  1729. /// off to this method to be emitted as notes.
  1730. ///
  1731. /// \param Overloads - The overloads to note.
  1732. /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
  1733. /// -fshow-overloads=best, this is the location to attach to the note about too
  1734. /// many candidates. Typically this will be the location of the original
  1735. /// ill-formed expression.
  1736. static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
  1737. const SourceLocation FinalNoteLoc) {
  1738. int ShownOverloads = 0;
  1739. int SuppressedOverloads = 0;
  1740. for (UnresolvedSetImpl::iterator It = Overloads.begin(),
  1741. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1742. // FIXME: Magic number for max shown overloads stolen from
  1743. // OverloadCandidateSet::NoteCandidates.
  1744. if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
  1745. ++SuppressedOverloads;
  1746. continue;
  1747. }
  1748. NamedDecl *Fn = (*It)->getUnderlyingDecl();
  1749. // Don't print overloads for non-default multiversioned functions.
  1750. if (const auto *FD = Fn->getAsFunction()) {
  1751. if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
  1752. !FD->getAttr<TargetAttr>()->isDefaultVersion())
  1753. continue;
  1754. }
  1755. S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
  1756. ++ShownOverloads;
  1757. }
  1758. if (SuppressedOverloads)
  1759. S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
  1760. << SuppressedOverloads;
  1761. }
  1762. static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
  1763. const UnresolvedSetImpl &Overloads,
  1764. bool (*IsPlausibleResult)(QualType)) {
  1765. if (!IsPlausibleResult)
  1766. return noteOverloads(S, Overloads, Loc);
  1767. UnresolvedSet<2> PlausibleOverloads;
  1768. for (OverloadExpr::decls_iterator It = Overloads.begin(),
  1769. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  1770. const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
  1771. QualType OverloadResultTy = OverloadDecl->getReturnType();
  1772. if (IsPlausibleResult(OverloadResultTy))
  1773. PlausibleOverloads.addDecl(It.getDecl());
  1774. }
  1775. noteOverloads(S, PlausibleOverloads, Loc);
  1776. }
  1777. /// Determine whether the given expression can be called by just
  1778. /// putting parentheses after it. Notably, expressions with unary
  1779. /// operators can't be because the unary operator will start parsing
  1780. /// outside the call.
  1781. static bool IsCallableWithAppend(Expr *E) {
  1782. E = E->IgnoreImplicit();
  1783. return (!isa<CStyleCastExpr>(E) &&
  1784. !isa<UnaryOperator>(E) &&
  1785. !isa<BinaryOperator>(E) &&
  1786. !isa<CXXOperatorCallExpr>(E));
  1787. }
  1788. static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
  1789. if (const auto *UO = dyn_cast<UnaryOperator>(E))
  1790. E = UO->getSubExpr();
  1791. if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  1792. if (ULE->getNumDecls() == 0)
  1793. return false;
  1794. const NamedDecl *ND = *ULE->decls_begin();
  1795. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  1796. return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
  1797. }
  1798. return false;
  1799. }
  1800. bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
  1801. bool ForceComplain,
  1802. bool (*IsPlausibleResult)(QualType)) {
  1803. SourceLocation Loc = E.get()->getExprLoc();
  1804. SourceRange Range = E.get()->getSourceRange();
  1805. QualType ZeroArgCallTy;
  1806. UnresolvedSet<4> Overloads;
  1807. if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
  1808. !ZeroArgCallTy.isNull() &&
  1809. (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
  1810. // At this point, we know E is potentially callable with 0
  1811. // arguments and that it returns something of a reasonable type,
  1812. // so we can emit a fixit and carry on pretending that E was
  1813. // actually a CallExpr.
  1814. SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
  1815. bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
  1816. Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
  1817. << (IsCallableWithAppend(E.get())
  1818. ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
  1819. : FixItHint());
  1820. if (!IsMV)
  1821. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1822. // FIXME: Try this before emitting the fixit, and suppress diagnostics
  1823. // while doing so.
  1824. E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
  1825. Range.getEnd().getLocWithOffset(1));
  1826. return true;
  1827. }
  1828. if (!ForceComplain) return false;
  1829. bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
  1830. Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
  1831. if (!IsMV)
  1832. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  1833. E = ExprError();
  1834. return true;
  1835. }
  1836. IdentifierInfo *Sema::getSuperIdentifier() const {
  1837. if (!Ident_super)
  1838. Ident_super = &Context.Idents.get("super");
  1839. return Ident_super;
  1840. }
  1841. IdentifierInfo *Sema::getFloat128Identifier() const {
  1842. if (!Ident___float128)
  1843. Ident___float128 = &Context.Idents.get("__float128");
  1844. return Ident___float128;
  1845. }
  1846. void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
  1847. CapturedRegionKind K) {
  1848. CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
  1849. getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
  1850. (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
  1851. CSI->ReturnType = Context.VoidTy;
  1852. FunctionScopes.push_back(CSI);
  1853. }
  1854. CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
  1855. if (FunctionScopes.empty())
  1856. return nullptr;
  1857. return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
  1858. }
  1859. const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
  1860. Sema::getMismatchingDeleteExpressions() const {
  1861. return DeleteExprs;
  1862. }
  1863. void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
  1864. if (ExtStr.empty())
  1865. return;
  1866. llvm::SmallVector<StringRef, 1> Exts;
  1867. ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
  1868. auto CanT = T.getCanonicalType().getTypePtr();
  1869. for (auto &I : Exts)
  1870. OpenCLTypeExtMap[CanT].insert(I.str());
  1871. }
  1872. void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
  1873. llvm::SmallVector<StringRef, 1> Exts;
  1874. ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
  1875. if (Exts.empty())
  1876. return;
  1877. for (auto &I : Exts)
  1878. OpenCLDeclExtMap[FD].insert(I.str());
  1879. }
  1880. void Sema::setCurrentOpenCLExtensionForType(QualType T) {
  1881. if (CurrOpenCLExtension.empty())
  1882. return;
  1883. setOpenCLExtensionForType(T, CurrOpenCLExtension);
  1884. }
  1885. void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
  1886. if (CurrOpenCLExtension.empty())
  1887. return;
  1888. setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
  1889. }
  1890. std::string Sema::getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD) {
  1891. if (!OpenCLDeclExtMap.empty())
  1892. return getOpenCLExtensionsFromExtMap(FD, OpenCLDeclExtMap);
  1893. return "";
  1894. }
  1895. std::string Sema::getOpenCLExtensionsFromTypeExtMap(FunctionType *FT) {
  1896. if (!OpenCLTypeExtMap.empty())
  1897. return getOpenCLExtensionsFromExtMap(FT, OpenCLTypeExtMap);
  1898. return "";
  1899. }
  1900. template <typename T, typename MapT>
  1901. std::string Sema::getOpenCLExtensionsFromExtMap(T *FDT, MapT &Map) {
  1902. std::string ExtensionNames = "";
  1903. auto Loc = Map.find(FDT);
  1904. for (auto const& I : Loc->second) {
  1905. ExtensionNames += I;
  1906. ExtensionNames += " ";
  1907. }
  1908. ExtensionNames.pop_back();
  1909. return ExtensionNames;
  1910. }
  1911. bool Sema::isOpenCLDisabledDecl(Decl *FD) {
  1912. auto Loc = OpenCLDeclExtMap.find(FD);
  1913. if (Loc == OpenCLDeclExtMap.end())
  1914. return false;
  1915. for (auto &I : Loc->second) {
  1916. if (!getOpenCLOptions().isEnabled(I))
  1917. return true;
  1918. }
  1919. return false;
  1920. }
  1921. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
  1922. bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
  1923. DiagInfoT DiagInfo, MapT &Map,
  1924. unsigned Selector,
  1925. SourceRange SrcRange) {
  1926. auto Loc = Map.find(D);
  1927. if (Loc == Map.end())
  1928. return false;
  1929. bool Disabled = false;
  1930. for (auto &I : Loc->second) {
  1931. if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
  1932. Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
  1933. << I << SrcRange;
  1934. Disabled = true;
  1935. }
  1936. }
  1937. return Disabled;
  1938. }
  1939. bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
  1940. // Check extensions for declared types.
  1941. Decl *Decl = nullptr;
  1942. if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
  1943. Decl = TypedefT->getDecl();
  1944. if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
  1945. Decl = TagT->getDecl();
  1946. auto Loc = DS.getTypeSpecTypeLoc();
  1947. // Check extensions for vector types.
  1948. // e.g. double4 is not allowed when cl_khr_fp64 is absent.
  1949. if (QT->isExtVectorType()) {
  1950. auto TypePtr = QT->castAs<ExtVectorType>()->getElementType().getTypePtr();
  1951. return checkOpenCLDisabledTypeOrDecl(TypePtr, Loc, QT, OpenCLTypeExtMap);
  1952. }
  1953. if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
  1954. return true;
  1955. // Check extensions for builtin types.
  1956. return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
  1957. QT, OpenCLTypeExtMap);
  1958. }
  1959. bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
  1960. IdentifierInfo *FnName = D.getIdentifier();
  1961. return checkOpenCLDisabledTypeOrDecl(&D, E.getBeginLoc(), FnName,
  1962. OpenCLDeclExtMap, 1, D.getSourceRange());
  1963. }