Sema.cpp 75 KB

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