Sema.cpp 87 KB

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