SemaTemplateInstantiate.cpp 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117
  1. //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
  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. // This file implements C++ template instantiation.
  9. //
  10. //===----------------------------------------------------------------------===/
  11. #include "clang/Sema/SemaInternal.h"
  12. #include "TreeTransform.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/PrettyDeclStackTrace.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Basic/Stack.h"
  22. #include "clang/Sema/DeclSpec.h"
  23. #include "clang/Sema/Initialization.h"
  24. #include "clang/Sema/Lookup.h"
  25. #include "clang/Sema/Template.h"
  26. #include "clang/Sema/TemplateDeduction.h"
  27. #include "clang/Sema/TemplateInstCallback.h"
  28. #include "llvm/Support/TimeProfiler.h"
  29. using namespace clang;
  30. using namespace sema;
  31. //===----------------------------------------------------------------------===/
  32. // Template Instantiation Support
  33. //===----------------------------------------------------------------------===/
  34. /// Retrieve the template argument list(s) that should be used to
  35. /// instantiate the definition of the given declaration.
  36. ///
  37. /// \param D the declaration for which we are computing template instantiation
  38. /// arguments.
  39. ///
  40. /// \param Innermost if non-NULL, the innermost template argument list.
  41. ///
  42. /// \param RelativeToPrimary true if we should get the template
  43. /// arguments relative to the primary template, even when we're
  44. /// dealing with a specialization. This is only relevant for function
  45. /// template specializations.
  46. ///
  47. /// \param Pattern If non-NULL, indicates the pattern from which we will be
  48. /// instantiating the definition of the given declaration, \p D. This is
  49. /// used to determine the proper set of template instantiation arguments for
  50. /// friend function template specializations.
  51. MultiLevelTemplateArgumentList
  52. Sema::getTemplateInstantiationArgs(NamedDecl *D,
  53. const TemplateArgumentList *Innermost,
  54. bool RelativeToPrimary,
  55. const FunctionDecl *Pattern) {
  56. // Accumulate the set of template argument lists in this structure.
  57. MultiLevelTemplateArgumentList Result;
  58. if (Innermost)
  59. Result.addOuterTemplateArguments(Innermost);
  60. DeclContext *Ctx = dyn_cast<DeclContext>(D);
  61. if (!Ctx) {
  62. Ctx = D->getDeclContext();
  63. // Add template arguments from a variable template instantiation. For a
  64. // class-scope explicit specialization, there are no template arguments
  65. // at this level, but there may be enclosing template arguments.
  66. VarTemplateSpecializationDecl *Spec =
  67. dyn_cast<VarTemplateSpecializationDecl>(D);
  68. if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
  69. // We're done when we hit an explicit specialization.
  70. if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
  71. !isa<VarTemplatePartialSpecializationDecl>(Spec))
  72. return Result;
  73. Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
  74. // If this variable template specialization was instantiated from a
  75. // specialized member that is a variable template, we're done.
  76. assert(Spec->getSpecializedTemplate() && "No variable template?");
  77. llvm::PointerUnion<VarTemplateDecl*,
  78. VarTemplatePartialSpecializationDecl*> Specialized
  79. = Spec->getSpecializedTemplateOrPartial();
  80. if (VarTemplatePartialSpecializationDecl *Partial =
  81. Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  82. if (Partial->isMemberSpecialization())
  83. return Result;
  84. } else {
  85. VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
  86. if (Tmpl->isMemberSpecialization())
  87. return Result;
  88. }
  89. }
  90. // If we have a template template parameter with translation unit context,
  91. // then we're performing substitution into a default template argument of
  92. // this template template parameter before we've constructed the template
  93. // that will own this template template parameter. In this case, we
  94. // use empty template parameter lists for all of the outer templates
  95. // to avoid performing any substitutions.
  96. if (Ctx->isTranslationUnit()) {
  97. if (TemplateTemplateParmDecl *TTP
  98. = dyn_cast<TemplateTemplateParmDecl>(D)) {
  99. for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
  100. Result.addOuterTemplateArguments(None);
  101. return Result;
  102. }
  103. }
  104. }
  105. while (!Ctx->isFileContext()) {
  106. // Add template arguments from a class template instantiation.
  107. ClassTemplateSpecializationDecl *Spec
  108. = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
  109. if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
  110. // We're done when we hit an explicit specialization.
  111. if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
  112. !isa<ClassTemplatePartialSpecializationDecl>(Spec))
  113. break;
  114. Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
  115. // If this class template specialization was instantiated from a
  116. // specialized member that is a class template, we're done.
  117. assert(Spec->getSpecializedTemplate() && "No class template?");
  118. if (Spec->getSpecializedTemplate()->isMemberSpecialization())
  119. break;
  120. }
  121. // Add template arguments from a function template specialization.
  122. else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
  123. if (!RelativeToPrimary &&
  124. Function->getTemplateSpecializationKindForInstantiation() ==
  125. TSK_ExplicitSpecialization)
  126. break;
  127. if (const TemplateArgumentList *TemplateArgs
  128. = Function->getTemplateSpecializationArgs()) {
  129. // Add the template arguments for this specialization.
  130. Result.addOuterTemplateArguments(TemplateArgs);
  131. // If this function was instantiated from a specialized member that is
  132. // a function template, we're done.
  133. assert(Function->getPrimaryTemplate() && "No function template?");
  134. if (Function->getPrimaryTemplate()->isMemberSpecialization())
  135. break;
  136. // If this function is a generic lambda specialization, we are done.
  137. if (isGenericLambdaCallOperatorSpecialization(Function))
  138. break;
  139. } else if (FunctionTemplateDecl *FunTmpl
  140. = Function->getDescribedFunctionTemplate()) {
  141. // Add the "injected" template arguments.
  142. Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
  143. }
  144. // If this is a friend declaration and it declares an entity at
  145. // namespace scope, take arguments from its lexical parent
  146. // instead of its semantic parent, unless of course the pattern we're
  147. // instantiating actually comes from the file's context!
  148. if (Function->getFriendObjectKind() &&
  149. Function->getDeclContext()->isFileContext() &&
  150. (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
  151. Ctx = Function->getLexicalDeclContext();
  152. RelativeToPrimary = false;
  153. continue;
  154. }
  155. } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
  156. if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
  157. QualType T = ClassTemplate->getInjectedClassNameSpecialization();
  158. const TemplateSpecializationType *TST =
  159. cast<TemplateSpecializationType>(Context.getCanonicalType(T));
  160. Result.addOuterTemplateArguments(
  161. llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
  162. if (ClassTemplate->isMemberSpecialization())
  163. break;
  164. }
  165. }
  166. Ctx = Ctx->getParent();
  167. RelativeToPrimary = false;
  168. }
  169. return Result;
  170. }
  171. bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
  172. switch (Kind) {
  173. case TemplateInstantiation:
  174. case ExceptionSpecInstantiation:
  175. case DefaultTemplateArgumentInstantiation:
  176. case DefaultFunctionArgumentInstantiation:
  177. case ExplicitTemplateArgumentSubstitution:
  178. case DeducedTemplateArgumentSubstitution:
  179. case PriorTemplateArgumentSubstitution:
  180. case ConstraintsCheck:
  181. return true;
  182. case DefaultTemplateArgumentChecking:
  183. case DeclaringSpecialMember:
  184. case DefiningSynthesizedFunction:
  185. case ExceptionSpecEvaluation:
  186. case ConstraintSubstitution:
  187. return false;
  188. // This function should never be called when Kind's value is Memoization.
  189. case Memoization:
  190. break;
  191. }
  192. llvm_unreachable("Invalid SynthesisKind!");
  193. }
  194. Sema::InstantiatingTemplate::InstantiatingTemplate(
  195. Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
  196. SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
  197. Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
  198. sema::TemplateDeductionInfo *DeductionInfo)
  199. : SemaRef(SemaRef) {
  200. // Don't allow further instantiation if a fatal error and an uncompilable
  201. // error have occurred. Any diagnostics we might have raised will not be
  202. // visible, and we do not need to construct a correct AST.
  203. if (SemaRef.Diags.hasFatalErrorOccurred() &&
  204. SemaRef.Diags.hasUncompilableErrorOccurred()) {
  205. Invalid = true;
  206. return;
  207. }
  208. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  209. if (!Invalid) {
  210. CodeSynthesisContext Inst;
  211. Inst.Kind = Kind;
  212. Inst.PointOfInstantiation = PointOfInstantiation;
  213. Inst.Entity = Entity;
  214. Inst.Template = Template;
  215. Inst.TemplateArgs = TemplateArgs.data();
  216. Inst.NumTemplateArgs = TemplateArgs.size();
  217. Inst.DeductionInfo = DeductionInfo;
  218. Inst.InstantiationRange = InstantiationRange;
  219. SemaRef.pushCodeSynthesisContext(Inst);
  220. AlreadyInstantiating =
  221. !SemaRef.InstantiatingSpecializations
  222. .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
  223. .second;
  224. atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
  225. }
  226. }
  227. Sema::InstantiatingTemplate::InstantiatingTemplate(
  228. Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
  229. SourceRange InstantiationRange)
  230. : InstantiatingTemplate(SemaRef,
  231. CodeSynthesisContext::TemplateInstantiation,
  232. PointOfInstantiation, InstantiationRange, Entity) {}
  233. Sema::InstantiatingTemplate::InstantiatingTemplate(
  234. Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
  235. ExceptionSpecification, SourceRange InstantiationRange)
  236. : InstantiatingTemplate(
  237. SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
  238. PointOfInstantiation, InstantiationRange, Entity) {}
  239. Sema::InstantiatingTemplate::InstantiatingTemplate(
  240. Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
  241. TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
  242. SourceRange InstantiationRange)
  243. : InstantiatingTemplate(
  244. SemaRef,
  245. CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
  246. PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
  247. Template, TemplateArgs) {}
  248. Sema::InstantiatingTemplate::InstantiatingTemplate(
  249. Sema &SemaRef, SourceLocation PointOfInstantiation,
  250. FunctionTemplateDecl *FunctionTemplate,
  251. ArrayRef<TemplateArgument> TemplateArgs,
  252. CodeSynthesisContext::SynthesisKind Kind,
  253. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  254. : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
  255. InstantiationRange, FunctionTemplate, nullptr,
  256. TemplateArgs, &DeductionInfo) {
  257. assert(
  258. Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
  259. Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
  260. }
  261. Sema::InstantiatingTemplate::InstantiatingTemplate(
  262. Sema &SemaRef, SourceLocation PointOfInstantiation,
  263. TemplateDecl *Template,
  264. ArrayRef<TemplateArgument> TemplateArgs,
  265. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  266. : InstantiatingTemplate(
  267. SemaRef,
  268. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  269. PointOfInstantiation, InstantiationRange, Template, nullptr,
  270. TemplateArgs, &DeductionInfo) {}
  271. Sema::InstantiatingTemplate::InstantiatingTemplate(
  272. Sema &SemaRef, SourceLocation PointOfInstantiation,
  273. ClassTemplatePartialSpecializationDecl *PartialSpec,
  274. ArrayRef<TemplateArgument> TemplateArgs,
  275. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  276. : InstantiatingTemplate(
  277. SemaRef,
  278. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  279. PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
  280. TemplateArgs, &DeductionInfo) {}
  281. Sema::InstantiatingTemplate::InstantiatingTemplate(
  282. Sema &SemaRef, SourceLocation PointOfInstantiation,
  283. VarTemplatePartialSpecializationDecl *PartialSpec,
  284. ArrayRef<TemplateArgument> TemplateArgs,
  285. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  286. : InstantiatingTemplate(
  287. SemaRef,
  288. CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
  289. PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
  290. TemplateArgs, &DeductionInfo) {}
  291. Sema::InstantiatingTemplate::InstantiatingTemplate(
  292. Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
  293. ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
  294. : InstantiatingTemplate(
  295. SemaRef,
  296. CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
  297. PointOfInstantiation, InstantiationRange, Param, nullptr,
  298. TemplateArgs) {}
  299. Sema::InstantiatingTemplate::InstantiatingTemplate(
  300. Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
  301. NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  302. SourceRange InstantiationRange)
  303. : InstantiatingTemplate(
  304. SemaRef,
  305. CodeSynthesisContext::PriorTemplateArgumentSubstitution,
  306. PointOfInstantiation, InstantiationRange, Param, Template,
  307. TemplateArgs) {}
  308. Sema::InstantiatingTemplate::InstantiatingTemplate(
  309. Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
  310. TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  311. SourceRange InstantiationRange)
  312. : InstantiatingTemplate(
  313. SemaRef,
  314. CodeSynthesisContext::PriorTemplateArgumentSubstitution,
  315. PointOfInstantiation, InstantiationRange, Param, Template,
  316. TemplateArgs) {}
  317. Sema::InstantiatingTemplate::InstantiatingTemplate(
  318. Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
  319. NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
  320. SourceRange InstantiationRange)
  321. : InstantiatingTemplate(
  322. SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
  323. PointOfInstantiation, InstantiationRange, Param, Template,
  324. TemplateArgs) {}
  325. Sema::InstantiatingTemplate::InstantiatingTemplate(
  326. Sema &SemaRef, SourceLocation PointOfInstantiation,
  327. ConstraintsCheck, TemplateDecl *Template,
  328. ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
  329. : InstantiatingTemplate(
  330. SemaRef, CodeSynthesisContext::ConstraintsCheck,
  331. PointOfInstantiation, InstantiationRange, Template, nullptr,
  332. TemplateArgs) {}
  333. Sema::InstantiatingTemplate::InstantiatingTemplate(
  334. Sema &SemaRef, SourceLocation PointOfInstantiation,
  335. ConstraintSubstitution, TemplateDecl *Template,
  336. sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
  337. : InstantiatingTemplate(
  338. SemaRef, CodeSynthesisContext::ConstraintSubstitution,
  339. PointOfInstantiation, InstantiationRange, Template, nullptr,
  340. {}, &DeductionInfo) {}
  341. void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
  342. Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
  343. InNonInstantiationSFINAEContext = false;
  344. CodeSynthesisContexts.push_back(Ctx);
  345. if (!Ctx.isInstantiationRecord())
  346. ++NonInstantiationEntries;
  347. // Check to see if we're low on stack space. We can't do anything about this
  348. // from here, but we can at least warn the user.
  349. if (isStackNearlyExhausted())
  350. warnStackExhausted(Ctx.PointOfInstantiation);
  351. }
  352. void Sema::popCodeSynthesisContext() {
  353. auto &Active = CodeSynthesisContexts.back();
  354. if (!Active.isInstantiationRecord()) {
  355. assert(NonInstantiationEntries > 0);
  356. --NonInstantiationEntries;
  357. }
  358. InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
  359. // Name lookup no longer looks in this template's defining module.
  360. assert(CodeSynthesisContexts.size() >=
  361. CodeSynthesisContextLookupModules.size() &&
  362. "forgot to remove a lookup module for a template instantiation");
  363. if (CodeSynthesisContexts.size() ==
  364. CodeSynthesisContextLookupModules.size()) {
  365. if (Module *M = CodeSynthesisContextLookupModules.back())
  366. LookupModulesCache.erase(M);
  367. CodeSynthesisContextLookupModules.pop_back();
  368. }
  369. // If we've left the code synthesis context for the current context stack,
  370. // stop remembering that we've emitted that stack.
  371. if (CodeSynthesisContexts.size() ==
  372. LastEmittedCodeSynthesisContextDepth)
  373. LastEmittedCodeSynthesisContextDepth = 0;
  374. CodeSynthesisContexts.pop_back();
  375. }
  376. void Sema::InstantiatingTemplate::Clear() {
  377. if (!Invalid) {
  378. if (!AlreadyInstantiating) {
  379. auto &Active = SemaRef.CodeSynthesisContexts.back();
  380. SemaRef.InstantiatingSpecializations.erase(
  381. std::make_pair(Active.Entity, Active.Kind));
  382. }
  383. atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
  384. SemaRef.CodeSynthesisContexts.back());
  385. SemaRef.popCodeSynthesisContext();
  386. Invalid = true;
  387. }
  388. }
  389. bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
  390. SourceLocation PointOfInstantiation,
  391. SourceRange InstantiationRange) {
  392. assert(SemaRef.NonInstantiationEntries <=
  393. SemaRef.CodeSynthesisContexts.size());
  394. if ((SemaRef.CodeSynthesisContexts.size() -
  395. SemaRef.NonInstantiationEntries)
  396. <= SemaRef.getLangOpts().InstantiationDepth)
  397. return false;
  398. SemaRef.Diag(PointOfInstantiation,
  399. diag::err_template_recursion_depth_exceeded)
  400. << SemaRef.getLangOpts().InstantiationDepth
  401. << InstantiationRange;
  402. SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
  403. << SemaRef.getLangOpts().InstantiationDepth;
  404. return true;
  405. }
  406. /// Prints the current instantiation stack through a series of
  407. /// notes.
  408. void Sema::PrintInstantiationStack() {
  409. // Determine which template instantiations to skip, if any.
  410. unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
  411. unsigned Limit = Diags.getTemplateBacktraceLimit();
  412. if (Limit && Limit < CodeSynthesisContexts.size()) {
  413. SkipStart = Limit / 2 + Limit % 2;
  414. SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
  415. }
  416. // FIXME: In all of these cases, we need to show the template arguments
  417. unsigned InstantiationIdx = 0;
  418. for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
  419. Active = CodeSynthesisContexts.rbegin(),
  420. ActiveEnd = CodeSynthesisContexts.rend();
  421. Active != ActiveEnd;
  422. ++Active, ++InstantiationIdx) {
  423. // Skip this instantiation?
  424. if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
  425. if (InstantiationIdx == SkipStart) {
  426. // Note that we're skipping instantiations.
  427. Diags.Report(Active->PointOfInstantiation,
  428. diag::note_instantiation_contexts_suppressed)
  429. << unsigned(CodeSynthesisContexts.size() - Limit);
  430. }
  431. continue;
  432. }
  433. switch (Active->Kind) {
  434. case CodeSynthesisContext::TemplateInstantiation: {
  435. Decl *D = Active->Entity;
  436. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  437. unsigned DiagID = diag::note_template_member_class_here;
  438. if (isa<ClassTemplateSpecializationDecl>(Record))
  439. DiagID = diag::note_template_class_instantiation_here;
  440. Diags.Report(Active->PointOfInstantiation, DiagID)
  441. << Record << Active->InstantiationRange;
  442. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  443. unsigned DiagID;
  444. if (Function->getPrimaryTemplate())
  445. DiagID = diag::note_function_template_spec_here;
  446. else
  447. DiagID = diag::note_template_member_function_here;
  448. Diags.Report(Active->PointOfInstantiation, DiagID)
  449. << Function
  450. << Active->InstantiationRange;
  451. } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  452. Diags.Report(Active->PointOfInstantiation,
  453. VD->isStaticDataMember()?
  454. diag::note_template_static_data_member_def_here
  455. : diag::note_template_variable_def_here)
  456. << VD
  457. << Active->InstantiationRange;
  458. } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  459. Diags.Report(Active->PointOfInstantiation,
  460. diag::note_template_enum_def_here)
  461. << ED
  462. << Active->InstantiationRange;
  463. } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  464. Diags.Report(Active->PointOfInstantiation,
  465. diag::note_template_nsdmi_here)
  466. << FD << Active->InstantiationRange;
  467. } else {
  468. Diags.Report(Active->PointOfInstantiation,
  469. diag::note_template_type_alias_instantiation_here)
  470. << cast<TypeAliasTemplateDecl>(D)
  471. << Active->InstantiationRange;
  472. }
  473. break;
  474. }
  475. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
  476. TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
  477. SmallVector<char, 128> TemplateArgsStr;
  478. llvm::raw_svector_ostream OS(TemplateArgsStr);
  479. Template->printName(OS);
  480. printTemplateArgumentList(OS, Active->template_arguments(),
  481. getPrintingPolicy());
  482. Diags.Report(Active->PointOfInstantiation,
  483. diag::note_default_arg_instantiation_here)
  484. << OS.str()
  485. << Active->InstantiationRange;
  486. break;
  487. }
  488. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
  489. FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
  490. Diags.Report(Active->PointOfInstantiation,
  491. diag::note_explicit_template_arg_substitution_here)
  492. << FnTmpl
  493. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  494. Active->TemplateArgs,
  495. Active->NumTemplateArgs)
  496. << Active->InstantiationRange;
  497. break;
  498. }
  499. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
  500. if (FunctionTemplateDecl *FnTmpl =
  501. dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
  502. Diags.Report(Active->PointOfInstantiation,
  503. diag::note_function_template_deduction_instantiation_here)
  504. << FnTmpl
  505. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  506. Active->TemplateArgs,
  507. Active->NumTemplateArgs)
  508. << Active->InstantiationRange;
  509. } else {
  510. bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
  511. isa<VarTemplateSpecializationDecl>(Active->Entity);
  512. bool IsTemplate = false;
  513. TemplateParameterList *Params;
  514. if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
  515. IsTemplate = true;
  516. Params = D->getTemplateParameters();
  517. } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
  518. Active->Entity)) {
  519. Params = D->getTemplateParameters();
  520. } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
  521. Active->Entity)) {
  522. Params = D->getTemplateParameters();
  523. } else {
  524. llvm_unreachable("unexpected template kind");
  525. }
  526. Diags.Report(Active->PointOfInstantiation,
  527. diag::note_deduced_template_arg_substitution_here)
  528. << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
  529. << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
  530. Active->NumTemplateArgs)
  531. << Active->InstantiationRange;
  532. }
  533. break;
  534. }
  535. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
  536. ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
  537. FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
  538. SmallVector<char, 128> TemplateArgsStr;
  539. llvm::raw_svector_ostream OS(TemplateArgsStr);
  540. FD->printName(OS);
  541. printTemplateArgumentList(OS, Active->template_arguments(),
  542. getPrintingPolicy());
  543. Diags.Report(Active->PointOfInstantiation,
  544. diag::note_default_function_arg_instantiation_here)
  545. << OS.str()
  546. << Active->InstantiationRange;
  547. break;
  548. }
  549. case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
  550. NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
  551. std::string Name;
  552. if (!Parm->getName().empty())
  553. Name = std::string(" '") + Parm->getName().str() + "'";
  554. TemplateParameterList *TemplateParams = nullptr;
  555. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  556. TemplateParams = Template->getTemplateParameters();
  557. else
  558. TemplateParams =
  559. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  560. ->getTemplateParameters();
  561. Diags.Report(Active->PointOfInstantiation,
  562. diag::note_prior_template_arg_substitution)
  563. << isa<TemplateTemplateParmDecl>(Parm)
  564. << Name
  565. << getTemplateArgumentBindingsText(TemplateParams,
  566. Active->TemplateArgs,
  567. Active->NumTemplateArgs)
  568. << Active->InstantiationRange;
  569. break;
  570. }
  571. case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
  572. TemplateParameterList *TemplateParams = nullptr;
  573. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  574. TemplateParams = Template->getTemplateParameters();
  575. else
  576. TemplateParams =
  577. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  578. ->getTemplateParameters();
  579. Diags.Report(Active->PointOfInstantiation,
  580. diag::note_template_default_arg_checking)
  581. << getTemplateArgumentBindingsText(TemplateParams,
  582. Active->TemplateArgs,
  583. Active->NumTemplateArgs)
  584. << Active->InstantiationRange;
  585. break;
  586. }
  587. case CodeSynthesisContext::ExceptionSpecEvaluation:
  588. Diags.Report(Active->PointOfInstantiation,
  589. diag::note_evaluating_exception_spec_here)
  590. << cast<FunctionDecl>(Active->Entity);
  591. break;
  592. case CodeSynthesisContext::ExceptionSpecInstantiation:
  593. Diags.Report(Active->PointOfInstantiation,
  594. diag::note_template_exception_spec_instantiation_here)
  595. << cast<FunctionDecl>(Active->Entity)
  596. << Active->InstantiationRange;
  597. break;
  598. case CodeSynthesisContext::DeclaringSpecialMember:
  599. Diags.Report(Active->PointOfInstantiation,
  600. diag::note_in_declaration_of_implicit_special_member)
  601. << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
  602. break;
  603. case CodeSynthesisContext::DefiningSynthesizedFunction: {
  604. // FIXME: For synthesized members other than special members, produce a note.
  605. auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
  606. auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
  607. if (CSM != CXXInvalid) {
  608. Diags.Report(Active->PointOfInstantiation,
  609. diag::note_member_synthesized_at)
  610. << CSM << Context.getTagDeclType(MD->getParent());
  611. }
  612. break;
  613. }
  614. case CodeSynthesisContext::Memoization:
  615. break;
  616. case CodeSynthesisContext::ConstraintsCheck:
  617. if (auto *CD = dyn_cast<ConceptDecl>(Active->Entity)) {
  618. SmallVector<char, 128> TemplateArgsStr;
  619. llvm::raw_svector_ostream OS(TemplateArgsStr);
  620. CD->printName(OS);
  621. printTemplateArgumentList(OS, Active->template_arguments(),
  622. getPrintingPolicy());
  623. Diags.Report(Active->PointOfInstantiation,
  624. diag::note_concept_specialization_here)
  625. << OS.str()
  626. << Active->InstantiationRange;
  627. break;
  628. }
  629. // TODO: Concepts - implement this for constrained templates and partial
  630. // specializations.
  631. llvm_unreachable("only concept constraints are supported right now");
  632. break;
  633. case CodeSynthesisContext::ConstraintSubstitution:
  634. Diags.Report(Active->PointOfInstantiation,
  635. diag::note_constraint_substitution_here)
  636. << Active->InstantiationRange;
  637. break;
  638. }
  639. }
  640. }
  641. Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
  642. if (InNonInstantiationSFINAEContext)
  643. return Optional<TemplateDeductionInfo *>(nullptr);
  644. for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
  645. Active = CodeSynthesisContexts.rbegin(),
  646. ActiveEnd = CodeSynthesisContexts.rend();
  647. Active != ActiveEnd;
  648. ++Active)
  649. {
  650. switch (Active->Kind) {
  651. case CodeSynthesisContext::TemplateInstantiation:
  652. // An instantiation of an alias template may or may not be a SFINAE
  653. // context, depending on what else is on the stack.
  654. if (isa<TypeAliasTemplateDecl>(Active->Entity))
  655. break;
  656. LLVM_FALLTHROUGH;
  657. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
  658. case CodeSynthesisContext::ExceptionSpecInstantiation:
  659. case CodeSynthesisContext::ConstraintsCheck:
  660. // This is a template instantiation, so there is no SFINAE.
  661. return None;
  662. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
  663. case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
  664. case CodeSynthesisContext::DefaultTemplateArgumentChecking:
  665. // A default template argument instantiation and substitution into
  666. // template parameters with arguments for prior parameters may or may
  667. // not be a SFINAE context; look further up the stack.
  668. break;
  669. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
  670. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
  671. case CodeSynthesisContext::ConstraintSubstitution:
  672. // We're either substituting explicitly-specified template arguments
  673. // or deduced template arguments or a constraint expression, so SFINAE
  674. // applies.
  675. assert(Active->DeductionInfo && "Missing deduction info pointer");
  676. return Active->DeductionInfo;
  677. case CodeSynthesisContext::DeclaringSpecialMember:
  678. case CodeSynthesisContext::DefiningSynthesizedFunction:
  679. // This happens in a context unrelated to template instantiation, so
  680. // there is no SFINAE.
  681. return None;
  682. case CodeSynthesisContext::ExceptionSpecEvaluation:
  683. // FIXME: This should not be treated as a SFINAE context, because
  684. // we will cache an incorrect exception specification. However, clang
  685. // bootstrap relies this! See PR31692.
  686. break;
  687. case CodeSynthesisContext::Memoization:
  688. break;
  689. }
  690. // The inner context was transparent for SFINAE. If it occurred within a
  691. // non-instantiation SFINAE context, then SFINAE applies.
  692. if (Active->SavedInNonInstantiationSFINAEContext)
  693. return Optional<TemplateDeductionInfo *>(nullptr);
  694. }
  695. return None;
  696. }
  697. //===----------------------------------------------------------------------===/
  698. // Template Instantiation for Types
  699. //===----------------------------------------------------------------------===/
  700. namespace {
  701. class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
  702. const MultiLevelTemplateArgumentList &TemplateArgs;
  703. SourceLocation Loc;
  704. DeclarationName Entity;
  705. public:
  706. typedef TreeTransform<TemplateInstantiator> inherited;
  707. TemplateInstantiator(Sema &SemaRef,
  708. const MultiLevelTemplateArgumentList &TemplateArgs,
  709. SourceLocation Loc,
  710. DeclarationName Entity)
  711. : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
  712. Entity(Entity) { }
  713. /// Determine whether the given type \p T has already been
  714. /// transformed.
  715. ///
  716. /// For the purposes of template instantiation, a type has already been
  717. /// transformed if it is NULL or if it is not dependent.
  718. bool AlreadyTransformed(QualType T);
  719. /// Returns the location of the entity being instantiated, if known.
  720. SourceLocation getBaseLocation() { return Loc; }
  721. /// Returns the name of the entity being instantiated, if any.
  722. DeclarationName getBaseEntity() { return Entity; }
  723. /// Sets the "base" location and entity when that
  724. /// information is known based on another transformation.
  725. void setBase(SourceLocation Loc, DeclarationName Entity) {
  726. this->Loc = Loc;
  727. this->Entity = Entity;
  728. }
  729. bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
  730. SourceRange PatternRange,
  731. ArrayRef<UnexpandedParameterPack> Unexpanded,
  732. bool &ShouldExpand, bool &RetainExpansion,
  733. Optional<unsigned> &NumExpansions) {
  734. return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
  735. PatternRange, Unexpanded,
  736. TemplateArgs,
  737. ShouldExpand,
  738. RetainExpansion,
  739. NumExpansions);
  740. }
  741. void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
  742. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
  743. }
  744. TemplateArgument ForgetPartiallySubstitutedPack() {
  745. TemplateArgument Result;
  746. if (NamedDecl *PartialPack
  747. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  748. MultiLevelTemplateArgumentList &TemplateArgs
  749. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  750. unsigned Depth, Index;
  751. std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  752. if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
  753. Result = TemplateArgs(Depth, Index);
  754. TemplateArgs.setArgument(Depth, Index, TemplateArgument());
  755. }
  756. }
  757. return Result;
  758. }
  759. void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
  760. if (Arg.isNull())
  761. return;
  762. if (NamedDecl *PartialPack
  763. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  764. MultiLevelTemplateArgumentList &TemplateArgs
  765. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  766. unsigned Depth, Index;
  767. std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  768. TemplateArgs.setArgument(Depth, Index, Arg);
  769. }
  770. }
  771. /// Transform the given declaration by instantiating a reference to
  772. /// this declaration.
  773. Decl *TransformDecl(SourceLocation Loc, Decl *D);
  774. void transformAttrs(Decl *Old, Decl *New) {
  775. SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
  776. }
  777. void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
  778. if (Old->isParameterPack()) {
  779. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
  780. for (auto *New : NewDecls)
  781. SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
  782. Old, cast<VarDecl>(New));
  783. return;
  784. }
  785. assert(NewDecls.size() == 1 &&
  786. "should only have multiple expansions for a pack");
  787. Decl *New = NewDecls.front();
  788. // If we've instantiated the call operator of a lambda or the call
  789. // operator template of a generic lambda, update the "instantiation of"
  790. // information.
  791. auto *NewMD = dyn_cast<CXXMethodDecl>(New);
  792. if (NewMD && isLambdaCallOperator(NewMD)) {
  793. auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
  794. if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
  795. NewTD->setInstantiatedFromMemberTemplate(
  796. OldMD->getDescribedFunctionTemplate());
  797. else
  798. NewMD->setInstantiationOfMemberFunction(OldMD,
  799. TSK_ImplicitInstantiation);
  800. }
  801. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
  802. // We recreated a local declaration, but not by instantiating it. There
  803. // may be pending dependent diagnostics to produce.
  804. if (auto *DC = dyn_cast<DeclContext>(Old))
  805. SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
  806. }
  807. /// Transform the definition of the given declaration by
  808. /// instantiating it.
  809. Decl *TransformDefinition(SourceLocation Loc, Decl *D);
  810. /// Transform the first qualifier within a scope by instantiating the
  811. /// declaration.
  812. NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
  813. /// Rebuild the exception declaration and register the declaration
  814. /// as an instantiated local.
  815. VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
  816. TypeSourceInfo *Declarator,
  817. SourceLocation StartLoc,
  818. SourceLocation NameLoc,
  819. IdentifierInfo *Name);
  820. /// Rebuild the Objective-C exception declaration and register the
  821. /// declaration as an instantiated local.
  822. VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  823. TypeSourceInfo *TSInfo, QualType T);
  824. /// Check for tag mismatches when instantiating an
  825. /// elaborated type.
  826. QualType RebuildElaboratedType(SourceLocation KeywordLoc,
  827. ElaboratedTypeKeyword Keyword,
  828. NestedNameSpecifierLoc QualifierLoc,
  829. QualType T);
  830. TemplateName
  831. TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
  832. SourceLocation NameLoc,
  833. QualType ObjectType = QualType(),
  834. NamedDecl *FirstQualifierInScope = nullptr,
  835. bool AllowInjectedClassName = false);
  836. const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
  837. ExprResult TransformPredefinedExpr(PredefinedExpr *E);
  838. ExprResult TransformDeclRefExpr(DeclRefExpr *E);
  839. ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
  840. ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
  841. NonTypeTemplateParmDecl *D);
  842. ExprResult TransformSubstNonTypeTemplateParmPackExpr(
  843. SubstNonTypeTemplateParmPackExpr *E);
  844. /// Rebuild a DeclRefExpr for a VarDecl reference.
  845. ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
  846. /// Transform a reference to a function or init-capture parameter pack.
  847. ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
  848. /// Transform a FunctionParmPackExpr which was built when we couldn't
  849. /// expand a function parameter pack reference which refers to an expanded
  850. /// pack.
  851. ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
  852. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  853. FunctionProtoTypeLoc TL) {
  854. // Call the base version; it will forward to our overridden version below.
  855. return inherited::TransformFunctionProtoType(TLB, TL);
  856. }
  857. template<typename Fn>
  858. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  859. FunctionProtoTypeLoc TL,
  860. CXXRecordDecl *ThisContext,
  861. Qualifiers ThisTypeQuals,
  862. Fn TransformExceptionSpec);
  863. ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
  864. int indexAdjustment,
  865. Optional<unsigned> NumExpansions,
  866. bool ExpectParameterPack);
  867. /// Transforms a template type parameter type by performing
  868. /// substitution of the corresponding template type argument.
  869. QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  870. TemplateTypeParmTypeLoc TL);
  871. /// Transforms an already-substituted template type parameter pack
  872. /// into either itself (if we aren't substituting into its pack expansion)
  873. /// or the appropriate substituted argument.
  874. QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
  875. SubstTemplateTypeParmPackTypeLoc TL);
  876. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  877. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  878. return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
  879. }
  880. TemplateParameterList *TransformTemplateParameterList(
  881. TemplateParameterList *OrigTPL) {
  882. if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
  883. DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
  884. TemplateDeclInstantiator DeclInstantiator(getSema(),
  885. /* DeclContext *Owner */ Owner, TemplateArgs);
  886. return DeclInstantiator.SubstTemplateParams(OrigTPL);
  887. }
  888. private:
  889. ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
  890. SourceLocation loc,
  891. TemplateArgument arg);
  892. };
  893. }
  894. bool TemplateInstantiator::AlreadyTransformed(QualType T) {
  895. if (T.isNull())
  896. return true;
  897. if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
  898. return false;
  899. getSema().MarkDeclarationsReferencedInType(Loc, T);
  900. return true;
  901. }
  902. static TemplateArgument
  903. getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
  904. assert(S.ArgumentPackSubstitutionIndex >= 0);
  905. assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  906. Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
  907. if (Arg.isPackExpansion())
  908. Arg = Arg.getPackExpansionPattern();
  909. return Arg;
  910. }
  911. Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
  912. if (!D)
  913. return nullptr;
  914. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
  915. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  916. // If the corresponding template argument is NULL or non-existent, it's
  917. // because we are performing instantiation from explicitly-specified
  918. // template arguments in a function template, but there were some
  919. // arguments left unspecified.
  920. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  921. TTP->getPosition()))
  922. return D;
  923. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  924. if (TTP->isParameterPack()) {
  925. assert(Arg.getKind() == TemplateArgument::Pack &&
  926. "Missing argument pack");
  927. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  928. }
  929. TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
  930. assert(!Template.isNull() && Template.getAsTemplateDecl() &&
  931. "Wrong kind of template template argument");
  932. return Template.getAsTemplateDecl();
  933. }
  934. // Fall through to find the instantiated declaration for this template
  935. // template parameter.
  936. }
  937. return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
  938. }
  939. Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
  940. Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
  941. if (!Inst)
  942. return nullptr;
  943. getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  944. return Inst;
  945. }
  946. NamedDecl *
  947. TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
  948. SourceLocation Loc) {
  949. // If the first part of the nested-name-specifier was a template type
  950. // parameter, instantiate that type parameter down to a tag type.
  951. if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
  952. const TemplateTypeParmType *TTP
  953. = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
  954. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  955. // FIXME: This needs testing w/ member access expressions.
  956. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
  957. if (TTP->isParameterPack()) {
  958. assert(Arg.getKind() == TemplateArgument::Pack &&
  959. "Missing argument pack");
  960. if (getSema().ArgumentPackSubstitutionIndex == -1)
  961. return nullptr;
  962. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  963. }
  964. QualType T = Arg.getAsType();
  965. if (T.isNull())
  966. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  967. if (const TagType *Tag = T->getAs<TagType>())
  968. return Tag->getDecl();
  969. // The resulting type is not a tag; complain.
  970. getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
  971. return nullptr;
  972. }
  973. }
  974. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  975. }
  976. VarDecl *
  977. TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
  978. TypeSourceInfo *Declarator,
  979. SourceLocation StartLoc,
  980. SourceLocation NameLoc,
  981. IdentifierInfo *Name) {
  982. VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
  983. StartLoc, NameLoc, Name);
  984. if (Var)
  985. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  986. return Var;
  987. }
  988. VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  989. TypeSourceInfo *TSInfo,
  990. QualType T) {
  991. VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
  992. if (Var)
  993. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  994. return Var;
  995. }
  996. QualType
  997. TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
  998. ElaboratedTypeKeyword Keyword,
  999. NestedNameSpecifierLoc QualifierLoc,
  1000. QualType T) {
  1001. if (const TagType *TT = T->getAs<TagType>()) {
  1002. TagDecl* TD = TT->getDecl();
  1003. SourceLocation TagLocation = KeywordLoc;
  1004. IdentifierInfo *Id = TD->getIdentifier();
  1005. // TODO: should we even warn on struct/class mismatches for this? Seems
  1006. // like it's likely to produce a lot of spurious errors.
  1007. if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
  1008. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
  1009. if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
  1010. TagLocation, Id)) {
  1011. SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
  1012. << Id
  1013. << FixItHint::CreateReplacement(SourceRange(TagLocation),
  1014. TD->getKindName());
  1015. SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
  1016. }
  1017. }
  1018. }
  1019. return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
  1020. Keyword,
  1021. QualifierLoc,
  1022. T);
  1023. }
  1024. TemplateName TemplateInstantiator::TransformTemplateName(
  1025. CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
  1026. QualType ObjectType, NamedDecl *FirstQualifierInScope,
  1027. bool AllowInjectedClassName) {
  1028. if (TemplateTemplateParmDecl *TTP
  1029. = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
  1030. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  1031. // If the corresponding template argument is NULL or non-existent, it's
  1032. // because we are performing instantiation from explicitly-specified
  1033. // template arguments in a function template, but there were some
  1034. // arguments left unspecified.
  1035. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  1036. TTP->getPosition()))
  1037. return Name;
  1038. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  1039. if (TTP->isParameterPack()) {
  1040. assert(Arg.getKind() == TemplateArgument::Pack &&
  1041. "Missing argument pack");
  1042. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1043. // We have the template argument pack to substitute, but we're not
  1044. // actually expanding the enclosing pack expansion yet. So, just
  1045. // keep the entire argument pack.
  1046. return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
  1047. }
  1048. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1049. }
  1050. TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
  1051. assert(!Template.isNull() && "Null template template argument");
  1052. assert(!Template.getAsQualifiedTemplateName() &&
  1053. "template decl to substitute is qualified?");
  1054. Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
  1055. return Template;
  1056. }
  1057. }
  1058. if (SubstTemplateTemplateParmPackStorage *SubstPack
  1059. = Name.getAsSubstTemplateTemplateParmPack()) {
  1060. if (getSema().ArgumentPackSubstitutionIndex == -1)
  1061. return Name;
  1062. TemplateArgument Arg = SubstPack->getArgumentPack();
  1063. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1064. return Arg.getAsTemplate().getNameToSubstitute();
  1065. }
  1066. return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
  1067. FirstQualifierInScope,
  1068. AllowInjectedClassName);
  1069. }
  1070. ExprResult
  1071. TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
  1072. if (!E->isTypeDependent())
  1073. return E;
  1074. return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
  1075. }
  1076. ExprResult
  1077. TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
  1078. NonTypeTemplateParmDecl *NTTP) {
  1079. // If the corresponding template argument is NULL or non-existent, it's
  1080. // because we are performing instantiation from explicitly-specified
  1081. // template arguments in a function template, but there were some
  1082. // arguments left unspecified.
  1083. if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
  1084. NTTP->getPosition()))
  1085. return E;
  1086. TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
  1087. if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
  1088. // We're performing a partial substitution, so the substituted argument
  1089. // could be dependent. As a result we can't create a SubstNonType*Expr
  1090. // node now, since that represents a fully-substituted argument.
  1091. // FIXME: We should have some AST representation for this.
  1092. if (Arg.getKind() == TemplateArgument::Pack) {
  1093. // FIXME: This won't work for alias templates.
  1094. assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
  1095. "unexpected pack arguments in partial substitution");
  1096. Arg = Arg.pack_begin()->getPackExpansionPattern();
  1097. }
  1098. assert(Arg.getKind() == TemplateArgument::Expression &&
  1099. "unexpected nontype template argument kind in partial substitution");
  1100. return Arg.getAsExpr();
  1101. }
  1102. if (NTTP->isParameterPack()) {
  1103. assert(Arg.getKind() == TemplateArgument::Pack &&
  1104. "Missing argument pack");
  1105. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1106. // We have an argument pack, but we can't select a particular argument
  1107. // out of it yet. Therefore, we'll build an expression to hold on to that
  1108. // argument pack.
  1109. QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
  1110. E->getLocation(),
  1111. NTTP->getDeclName());
  1112. if (TargetType.isNull())
  1113. return ExprError();
  1114. return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
  1115. TargetType.getNonLValueExprType(SemaRef.Context),
  1116. TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
  1117. E->getLocation(), Arg);
  1118. }
  1119. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1120. }
  1121. return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
  1122. }
  1123. const LoopHintAttr *
  1124. TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
  1125. Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
  1126. if (TransformedExpr == LH->getValue())
  1127. return LH;
  1128. // Generate error if there is a problem with the value.
  1129. if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
  1130. return LH;
  1131. // Create new LoopHintValueAttr with integral expression in place of the
  1132. // non-type template parameter.
  1133. return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
  1134. LH->getState(), TransformedExpr, *LH);
  1135. }
  1136. ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
  1137. NonTypeTemplateParmDecl *parm,
  1138. SourceLocation loc,
  1139. TemplateArgument arg) {
  1140. ExprResult result;
  1141. QualType type;
  1142. // The template argument itself might be an expression, in which
  1143. // case we just return that expression.
  1144. if (arg.getKind() == TemplateArgument::Expression) {
  1145. Expr *argExpr = arg.getAsExpr();
  1146. result = argExpr;
  1147. type = argExpr->getType();
  1148. } else if (arg.getKind() == TemplateArgument::Declaration ||
  1149. arg.getKind() == TemplateArgument::NullPtr) {
  1150. ValueDecl *VD;
  1151. if (arg.getKind() == TemplateArgument::Declaration) {
  1152. VD = arg.getAsDecl();
  1153. // Find the instantiation of the template argument. This is
  1154. // required for nested templates.
  1155. VD = cast_or_null<ValueDecl>(
  1156. getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
  1157. if (!VD)
  1158. return ExprError();
  1159. } else {
  1160. // Propagate NULL template argument.
  1161. VD = nullptr;
  1162. }
  1163. // Derive the type we want the substituted decl to have. This had
  1164. // better be non-dependent, or these checks will have serious problems.
  1165. if (parm->isExpandedParameterPack()) {
  1166. type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
  1167. } else if (parm->isParameterPack() &&
  1168. isa<PackExpansionType>(parm->getType())) {
  1169. type = SemaRef.SubstType(
  1170. cast<PackExpansionType>(parm->getType())->getPattern(),
  1171. TemplateArgs, loc, parm->getDeclName());
  1172. } else {
  1173. type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
  1174. TemplateArgs, loc, parm->getDeclName());
  1175. }
  1176. assert(!type.isNull() && "type substitution failed for param type");
  1177. assert(!type->isDependentType() && "param type still dependent");
  1178. result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
  1179. if (!result.isInvalid()) type = result.get()->getType();
  1180. } else {
  1181. result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
  1182. // Note that this type can be different from the type of 'result',
  1183. // e.g. if it's an enum type.
  1184. type = arg.getIntegralType();
  1185. }
  1186. if (result.isInvalid()) return ExprError();
  1187. Expr *resultExpr = result.get();
  1188. return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
  1189. type, resultExpr->getValueKind(), loc, parm, resultExpr);
  1190. }
  1191. ExprResult
  1192. TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
  1193. SubstNonTypeTemplateParmPackExpr *E) {
  1194. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1195. // We aren't expanding the parameter pack, so just return ourselves.
  1196. return E;
  1197. }
  1198. TemplateArgument Arg = E->getArgumentPack();
  1199. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1200. return transformNonTypeTemplateParmRef(E->getParameterPack(),
  1201. E->getParameterPackLocation(),
  1202. Arg);
  1203. }
  1204. ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
  1205. SourceLocation Loc) {
  1206. DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
  1207. return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
  1208. }
  1209. ExprResult
  1210. TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
  1211. if (getSema().ArgumentPackSubstitutionIndex != -1) {
  1212. // We can expand this parameter pack now.
  1213. VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
  1214. VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
  1215. if (!VD)
  1216. return ExprError();
  1217. return RebuildVarDeclRefExpr(VD, E->getExprLoc());
  1218. }
  1219. QualType T = TransformType(E->getType());
  1220. if (T.isNull())
  1221. return ExprError();
  1222. // Transform each of the parameter expansions into the corresponding
  1223. // parameters in the instantiation of the function decl.
  1224. SmallVector<VarDecl *, 8> Vars;
  1225. Vars.reserve(E->getNumExpansions());
  1226. for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
  1227. I != End; ++I) {
  1228. VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
  1229. if (!D)
  1230. return ExprError();
  1231. Vars.push_back(D);
  1232. }
  1233. auto *PackExpr =
  1234. FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
  1235. E->getParameterPackLocation(), Vars);
  1236. getSema().MarkFunctionParmPackReferenced(PackExpr);
  1237. return PackExpr;
  1238. }
  1239. ExprResult
  1240. TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
  1241. VarDecl *PD) {
  1242. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  1243. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
  1244. = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
  1245. assert(Found && "no instantiation for parameter pack");
  1246. Decl *TransformedDecl;
  1247. if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
  1248. // If this is a reference to a function parameter pack which we can
  1249. // substitute but can't yet expand, build a FunctionParmPackExpr for it.
  1250. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1251. QualType T = TransformType(E->getType());
  1252. if (T.isNull())
  1253. return ExprError();
  1254. auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
  1255. E->getExprLoc(), *Pack);
  1256. getSema().MarkFunctionParmPackReferenced(PackExpr);
  1257. return PackExpr;
  1258. }
  1259. TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
  1260. } else {
  1261. TransformedDecl = Found->get<Decl*>();
  1262. }
  1263. // We have either an unexpanded pack or a specific expansion.
  1264. return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
  1265. }
  1266. ExprResult
  1267. TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
  1268. NamedDecl *D = E->getDecl();
  1269. // Handle references to non-type template parameters and non-type template
  1270. // parameter packs.
  1271. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
  1272. if (NTTP->getDepth() < TemplateArgs.getNumLevels())
  1273. return TransformTemplateParmRefExpr(E, NTTP);
  1274. // We have a non-type template parameter that isn't fully substituted;
  1275. // FindInstantiatedDecl will find it in the local instantiation scope.
  1276. }
  1277. // Handle references to function parameter packs.
  1278. if (VarDecl *PD = dyn_cast<VarDecl>(D))
  1279. if (PD->isParameterPack())
  1280. return TransformFunctionParmPackRefExpr(E, PD);
  1281. return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
  1282. }
  1283. ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
  1284. CXXDefaultArgExpr *E) {
  1285. assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
  1286. getDescribedFunctionTemplate() &&
  1287. "Default arg expressions are never formed in dependent cases.");
  1288. return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
  1289. cast<FunctionDecl>(E->getParam()->getDeclContext()),
  1290. E->getParam());
  1291. }
  1292. template<typename Fn>
  1293. QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
  1294. FunctionProtoTypeLoc TL,
  1295. CXXRecordDecl *ThisContext,
  1296. Qualifiers ThisTypeQuals,
  1297. Fn TransformExceptionSpec) {
  1298. // We need a local instantiation scope for this function prototype.
  1299. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  1300. return inherited::TransformFunctionProtoType(
  1301. TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
  1302. }
  1303. ParmVarDecl *
  1304. TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
  1305. int indexAdjustment,
  1306. Optional<unsigned> NumExpansions,
  1307. bool ExpectParameterPack) {
  1308. return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
  1309. NumExpansions, ExpectParameterPack);
  1310. }
  1311. QualType
  1312. TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  1313. TemplateTypeParmTypeLoc TL) {
  1314. const TemplateTypeParmType *T = TL.getTypePtr();
  1315. if (T->getDepth() < TemplateArgs.getNumLevels()) {
  1316. // Replace the template type parameter with its corresponding
  1317. // template argument.
  1318. // If the corresponding template argument is NULL or doesn't exist, it's
  1319. // because we are performing instantiation from explicitly-specified
  1320. // template arguments in a function template class, but there were some
  1321. // arguments left unspecified.
  1322. if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
  1323. TemplateTypeParmTypeLoc NewTL
  1324. = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
  1325. NewTL.setNameLoc(TL.getNameLoc());
  1326. return TL.getType();
  1327. }
  1328. TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
  1329. if (T->isParameterPack()) {
  1330. assert(Arg.getKind() == TemplateArgument::Pack &&
  1331. "Missing argument pack");
  1332. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1333. // We have the template argument pack, but we're not expanding the
  1334. // enclosing pack expansion yet. Just save the template argument
  1335. // pack for later substitution.
  1336. QualType Result
  1337. = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
  1338. SubstTemplateTypeParmPackTypeLoc NewTL
  1339. = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
  1340. NewTL.setNameLoc(TL.getNameLoc());
  1341. return Result;
  1342. }
  1343. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1344. }
  1345. assert(Arg.getKind() == TemplateArgument::Type &&
  1346. "Template argument kind mismatch");
  1347. QualType Replacement = Arg.getAsType();
  1348. // TODO: only do this uniquing once, at the start of instantiation.
  1349. QualType Result
  1350. = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
  1351. SubstTemplateTypeParmTypeLoc NewTL
  1352. = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
  1353. NewTL.setNameLoc(TL.getNameLoc());
  1354. return Result;
  1355. }
  1356. // The template type parameter comes from an inner template (e.g.,
  1357. // the template parameter list of a member template inside the
  1358. // template we are instantiating). Create a new template type
  1359. // parameter with the template "level" reduced by one.
  1360. TemplateTypeParmDecl *NewTTPDecl = nullptr;
  1361. if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
  1362. NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
  1363. TransformDecl(TL.getNameLoc(), OldTTPDecl));
  1364. QualType Result = getSema().Context.getTemplateTypeParmType(
  1365. T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
  1366. T->isParameterPack(), NewTTPDecl);
  1367. TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
  1368. NewTL.setNameLoc(TL.getNameLoc());
  1369. return Result;
  1370. }
  1371. QualType
  1372. TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
  1373. TypeLocBuilder &TLB,
  1374. SubstTemplateTypeParmPackTypeLoc TL) {
  1375. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1376. // We aren't expanding the parameter pack, so just return ourselves.
  1377. SubstTemplateTypeParmPackTypeLoc NewTL
  1378. = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
  1379. NewTL.setNameLoc(TL.getNameLoc());
  1380. return TL.getType();
  1381. }
  1382. TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
  1383. Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
  1384. QualType Result = Arg.getAsType();
  1385. Result = getSema().Context.getSubstTemplateTypeParmType(
  1386. TL.getTypePtr()->getReplacedParameter(),
  1387. Result);
  1388. SubstTemplateTypeParmTypeLoc NewTL
  1389. = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
  1390. NewTL.setNameLoc(TL.getNameLoc());
  1391. return Result;
  1392. }
  1393. /// Perform substitution on the type T with a given set of template
  1394. /// arguments.
  1395. ///
  1396. /// This routine substitutes the given template arguments into the
  1397. /// type T and produces the instantiated type.
  1398. ///
  1399. /// \param T the type into which the template arguments will be
  1400. /// substituted. If this type is not dependent, it will be returned
  1401. /// immediately.
  1402. ///
  1403. /// \param Args the template arguments that will be
  1404. /// substituted for the top-level template parameters within T.
  1405. ///
  1406. /// \param Loc the location in the source code where this substitution
  1407. /// is being performed. It will typically be the location of the
  1408. /// declarator (if we're instantiating the type of some declaration)
  1409. /// or the location of the type in the source code (if, e.g., we're
  1410. /// instantiating the type of a cast expression).
  1411. ///
  1412. /// \param Entity the name of the entity associated with a declaration
  1413. /// being instantiated (if any). May be empty to indicate that there
  1414. /// is no such entity (if, e.g., this is a type that occurs as part of
  1415. /// a cast expression) or that the entity has no name (e.g., an
  1416. /// unnamed function parameter).
  1417. ///
  1418. /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
  1419. /// acceptable as the top level type of the result.
  1420. ///
  1421. /// \returns If the instantiation succeeds, the instantiated
  1422. /// type. Otherwise, produces diagnostics and returns a NULL type.
  1423. TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
  1424. const MultiLevelTemplateArgumentList &Args,
  1425. SourceLocation Loc,
  1426. DeclarationName Entity,
  1427. bool AllowDeducedTST) {
  1428. assert(!CodeSynthesisContexts.empty() &&
  1429. "Cannot perform an instantiation without some context on the "
  1430. "instantiation stack");
  1431. if (!T->getType()->isInstantiationDependentType() &&
  1432. !T->getType()->isVariablyModifiedType())
  1433. return T;
  1434. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1435. return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
  1436. : Instantiator.TransformType(T);
  1437. }
  1438. TypeSourceInfo *Sema::SubstType(TypeLoc TL,
  1439. const MultiLevelTemplateArgumentList &Args,
  1440. SourceLocation Loc,
  1441. DeclarationName Entity) {
  1442. assert(!CodeSynthesisContexts.empty() &&
  1443. "Cannot perform an instantiation without some context on the "
  1444. "instantiation stack");
  1445. if (TL.getType().isNull())
  1446. return nullptr;
  1447. if (!TL.getType()->isInstantiationDependentType() &&
  1448. !TL.getType()->isVariablyModifiedType()) {
  1449. // FIXME: Make a copy of the TypeLoc data here, so that we can
  1450. // return a new TypeSourceInfo. Inefficient!
  1451. TypeLocBuilder TLB;
  1452. TLB.pushFullCopy(TL);
  1453. return TLB.getTypeSourceInfo(Context, TL.getType());
  1454. }
  1455. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1456. TypeLocBuilder TLB;
  1457. TLB.reserve(TL.getFullDataSize());
  1458. QualType Result = Instantiator.TransformType(TLB, TL);
  1459. if (Result.isNull())
  1460. return nullptr;
  1461. return TLB.getTypeSourceInfo(Context, Result);
  1462. }
  1463. /// Deprecated form of the above.
  1464. QualType Sema::SubstType(QualType T,
  1465. const MultiLevelTemplateArgumentList &TemplateArgs,
  1466. SourceLocation Loc, DeclarationName Entity) {
  1467. assert(!CodeSynthesisContexts.empty() &&
  1468. "Cannot perform an instantiation without some context on the "
  1469. "instantiation stack");
  1470. // If T is not a dependent type or a variably-modified type, there
  1471. // is nothing to do.
  1472. if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
  1473. return T;
  1474. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
  1475. return Instantiator.TransformType(T);
  1476. }
  1477. static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
  1478. if (T->getType()->isInstantiationDependentType() ||
  1479. T->getType()->isVariablyModifiedType())
  1480. return true;
  1481. TypeLoc TL = T->getTypeLoc().IgnoreParens();
  1482. if (!TL.getAs<FunctionProtoTypeLoc>())
  1483. return false;
  1484. FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
  1485. for (ParmVarDecl *P : FP.getParams()) {
  1486. // This must be synthesized from a typedef.
  1487. if (!P) continue;
  1488. // If there are any parameters, a new TypeSourceInfo that refers to the
  1489. // instantiated parameters must be built.
  1490. return true;
  1491. }
  1492. return false;
  1493. }
  1494. /// A form of SubstType intended specifically for instantiating the
  1495. /// type of a FunctionDecl. Its purpose is solely to force the
  1496. /// instantiation of default-argument expressions and to avoid
  1497. /// instantiating an exception-specification.
  1498. TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
  1499. const MultiLevelTemplateArgumentList &Args,
  1500. SourceLocation Loc,
  1501. DeclarationName Entity,
  1502. CXXRecordDecl *ThisContext,
  1503. Qualifiers ThisTypeQuals) {
  1504. assert(!CodeSynthesisContexts.empty() &&
  1505. "Cannot perform an instantiation without some context on the "
  1506. "instantiation stack");
  1507. if (!NeedsInstantiationAsFunctionType(T))
  1508. return T;
  1509. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1510. TypeLocBuilder TLB;
  1511. TypeLoc TL = T->getTypeLoc();
  1512. TLB.reserve(TL.getFullDataSize());
  1513. QualType Result;
  1514. if (FunctionProtoTypeLoc Proto =
  1515. TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
  1516. // Instantiate the type, other than its exception specification. The
  1517. // exception specification is instantiated in InitFunctionInstantiation
  1518. // once we've built the FunctionDecl.
  1519. // FIXME: Set the exception specification to EST_Uninstantiated here,
  1520. // instead of rebuilding the function type again later.
  1521. Result = Instantiator.TransformFunctionProtoType(
  1522. TLB, Proto, ThisContext, ThisTypeQuals,
  1523. [](FunctionProtoType::ExceptionSpecInfo &ESI,
  1524. bool &Changed) { return false; });
  1525. } else {
  1526. Result = Instantiator.TransformType(TLB, TL);
  1527. }
  1528. if (Result.isNull())
  1529. return nullptr;
  1530. return TLB.getTypeSourceInfo(Context, Result);
  1531. }
  1532. bool Sema::SubstExceptionSpec(SourceLocation Loc,
  1533. FunctionProtoType::ExceptionSpecInfo &ESI,
  1534. SmallVectorImpl<QualType> &ExceptionStorage,
  1535. const MultiLevelTemplateArgumentList &Args) {
  1536. assert(ESI.Type != EST_Uninstantiated);
  1537. bool Changed = false;
  1538. TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
  1539. return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
  1540. Changed);
  1541. }
  1542. void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
  1543. const MultiLevelTemplateArgumentList &Args) {
  1544. FunctionProtoType::ExceptionSpecInfo ESI =
  1545. Proto->getExtProtoInfo().ExceptionSpec;
  1546. SmallVector<QualType, 4> ExceptionStorage;
  1547. if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
  1548. ESI, ExceptionStorage, Args))
  1549. // On error, recover by dropping the exception specification.
  1550. ESI.Type = EST_None;
  1551. UpdateExceptionSpec(New, ESI);
  1552. }
  1553. ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
  1554. const MultiLevelTemplateArgumentList &TemplateArgs,
  1555. int indexAdjustment,
  1556. Optional<unsigned> NumExpansions,
  1557. bool ExpectParameterPack) {
  1558. TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
  1559. TypeSourceInfo *NewDI = nullptr;
  1560. TypeLoc OldTL = OldDI->getTypeLoc();
  1561. if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
  1562. // We have a function parameter pack. Substitute into the pattern of the
  1563. // expansion.
  1564. NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
  1565. OldParm->getLocation(), OldParm->getDeclName());
  1566. if (!NewDI)
  1567. return nullptr;
  1568. if (NewDI->getType()->containsUnexpandedParameterPack()) {
  1569. // We still have unexpanded parameter packs, which means that
  1570. // our function parameter is still a function parameter pack.
  1571. // Therefore, make its type a pack expansion type.
  1572. NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
  1573. NumExpansions);
  1574. } else if (ExpectParameterPack) {
  1575. // We expected to get a parameter pack but didn't (because the type
  1576. // itself is not a pack expansion type), so complain. This can occur when
  1577. // the substitution goes through an alias template that "loses" the
  1578. // pack expansion.
  1579. Diag(OldParm->getLocation(),
  1580. diag::err_function_parameter_pack_without_parameter_packs)
  1581. << NewDI->getType();
  1582. return nullptr;
  1583. }
  1584. } else {
  1585. NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
  1586. OldParm->getDeclName());
  1587. }
  1588. if (!NewDI)
  1589. return nullptr;
  1590. if (NewDI->getType()->isVoidType()) {
  1591. Diag(OldParm->getLocation(), diag::err_param_with_void_type);
  1592. return nullptr;
  1593. }
  1594. ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
  1595. OldParm->getInnerLocStart(),
  1596. OldParm->getLocation(),
  1597. OldParm->getIdentifier(),
  1598. NewDI->getType(), NewDI,
  1599. OldParm->getStorageClass());
  1600. if (!NewParm)
  1601. return nullptr;
  1602. // Mark the (new) default argument as uninstantiated (if any).
  1603. if (OldParm->hasUninstantiatedDefaultArg()) {
  1604. Expr *Arg = OldParm->getUninstantiatedDefaultArg();
  1605. NewParm->setUninstantiatedDefaultArg(Arg);
  1606. } else if (OldParm->hasUnparsedDefaultArg()) {
  1607. NewParm->setUnparsedDefaultArg();
  1608. UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
  1609. } else if (Expr *Arg = OldParm->getDefaultArg()) {
  1610. FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
  1611. if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
  1612. // Instantiate default arguments for methods of local classes (DR1484)
  1613. // and non-defining declarations.
  1614. Sema::ContextRAII SavedContext(*this, OwningFunc);
  1615. LocalInstantiationScope Local(*this, true);
  1616. ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
  1617. if (NewArg.isUsable()) {
  1618. // It would be nice if we still had this.
  1619. SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
  1620. SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
  1621. }
  1622. } else {
  1623. // FIXME: if we non-lazily instantiated non-dependent default args for
  1624. // non-dependent parameter types we could remove a bunch of duplicate
  1625. // conversion warnings for such arguments.
  1626. NewParm->setUninstantiatedDefaultArg(Arg);
  1627. }
  1628. }
  1629. NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
  1630. if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
  1631. // Add the new parameter to the instantiated parameter pack.
  1632. CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
  1633. } else {
  1634. // Introduce an Old -> New mapping
  1635. CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
  1636. }
  1637. // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
  1638. // can be anything, is this right ?
  1639. NewParm->setDeclContext(CurContext);
  1640. NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
  1641. OldParm->getFunctionScopeIndex() + indexAdjustment);
  1642. InstantiateAttrs(TemplateArgs, OldParm, NewParm);
  1643. return NewParm;
  1644. }
  1645. /// Substitute the given template arguments into the given set of
  1646. /// parameters, producing the set of parameter types that would be generated
  1647. /// from such a substitution.
  1648. bool Sema::SubstParmTypes(
  1649. SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
  1650. const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
  1651. const MultiLevelTemplateArgumentList &TemplateArgs,
  1652. SmallVectorImpl<QualType> &ParamTypes,
  1653. SmallVectorImpl<ParmVarDecl *> *OutParams,
  1654. ExtParameterInfoBuilder &ParamInfos) {
  1655. assert(!CodeSynthesisContexts.empty() &&
  1656. "Cannot perform an instantiation without some context on the "
  1657. "instantiation stack");
  1658. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  1659. DeclarationName());
  1660. return Instantiator.TransformFunctionTypeParams(
  1661. Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
  1662. }
  1663. /// Perform substitution on the base class specifiers of the
  1664. /// given class template specialization.
  1665. ///
  1666. /// Produces a diagnostic and returns true on error, returns false and
  1667. /// attaches the instantiated base classes to the class template
  1668. /// specialization if successful.
  1669. bool
  1670. Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
  1671. CXXRecordDecl *Pattern,
  1672. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1673. bool Invalid = false;
  1674. SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
  1675. for (const auto &Base : Pattern->bases()) {
  1676. if (!Base.getType()->isDependentType()) {
  1677. if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
  1678. if (RD->isInvalidDecl())
  1679. Instantiation->setInvalidDecl();
  1680. }
  1681. InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
  1682. continue;
  1683. }
  1684. SourceLocation EllipsisLoc;
  1685. TypeSourceInfo *BaseTypeLoc;
  1686. if (Base.isPackExpansion()) {
  1687. // This is a pack expansion. See whether we should expand it now, or
  1688. // wait until later.
  1689. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1690. collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
  1691. Unexpanded);
  1692. bool ShouldExpand = false;
  1693. bool RetainExpansion = false;
  1694. Optional<unsigned> NumExpansions;
  1695. if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
  1696. Base.getSourceRange(),
  1697. Unexpanded,
  1698. TemplateArgs, ShouldExpand,
  1699. RetainExpansion,
  1700. NumExpansions)) {
  1701. Invalid = true;
  1702. continue;
  1703. }
  1704. // If we should expand this pack expansion now, do so.
  1705. if (ShouldExpand) {
  1706. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1707. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  1708. TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  1709. TemplateArgs,
  1710. Base.getSourceRange().getBegin(),
  1711. DeclarationName());
  1712. if (!BaseTypeLoc) {
  1713. Invalid = true;
  1714. continue;
  1715. }
  1716. if (CXXBaseSpecifier *InstantiatedBase
  1717. = CheckBaseSpecifier(Instantiation,
  1718. Base.getSourceRange(),
  1719. Base.isVirtual(),
  1720. Base.getAccessSpecifierAsWritten(),
  1721. BaseTypeLoc,
  1722. SourceLocation()))
  1723. InstantiatedBases.push_back(InstantiatedBase);
  1724. else
  1725. Invalid = true;
  1726. }
  1727. continue;
  1728. }
  1729. // The resulting base specifier will (still) be a pack expansion.
  1730. EllipsisLoc = Base.getEllipsisLoc();
  1731. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  1732. BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  1733. TemplateArgs,
  1734. Base.getSourceRange().getBegin(),
  1735. DeclarationName());
  1736. } else {
  1737. BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
  1738. TemplateArgs,
  1739. Base.getSourceRange().getBegin(),
  1740. DeclarationName());
  1741. }
  1742. if (!BaseTypeLoc) {
  1743. Invalid = true;
  1744. continue;
  1745. }
  1746. if (CXXBaseSpecifier *InstantiatedBase
  1747. = CheckBaseSpecifier(Instantiation,
  1748. Base.getSourceRange(),
  1749. Base.isVirtual(),
  1750. Base.getAccessSpecifierAsWritten(),
  1751. BaseTypeLoc,
  1752. EllipsisLoc))
  1753. InstantiatedBases.push_back(InstantiatedBase);
  1754. else
  1755. Invalid = true;
  1756. }
  1757. if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
  1758. Invalid = true;
  1759. return Invalid;
  1760. }
  1761. // Defined via #include from SemaTemplateInstantiateDecl.cpp
  1762. namespace clang {
  1763. namespace sema {
  1764. Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
  1765. const MultiLevelTemplateArgumentList &TemplateArgs);
  1766. Attr *instantiateTemplateAttributeForDecl(
  1767. const Attr *At, ASTContext &C, Sema &S,
  1768. const MultiLevelTemplateArgumentList &TemplateArgs);
  1769. }
  1770. }
  1771. /// Instantiate the definition of a class from a given pattern.
  1772. ///
  1773. /// \param PointOfInstantiation The point of instantiation within the
  1774. /// source code.
  1775. ///
  1776. /// \param Instantiation is the declaration whose definition is being
  1777. /// instantiated. This will be either a class template specialization
  1778. /// or a member class of a class template specialization.
  1779. ///
  1780. /// \param Pattern is the pattern from which the instantiation
  1781. /// occurs. This will be either the declaration of a class template or
  1782. /// the declaration of a member class of a class template.
  1783. ///
  1784. /// \param TemplateArgs The template arguments to be substituted into
  1785. /// the pattern.
  1786. ///
  1787. /// \param TSK the kind of implicit or explicit instantiation to perform.
  1788. ///
  1789. /// \param Complain whether to complain if the class cannot be instantiated due
  1790. /// to the lack of a definition.
  1791. ///
  1792. /// \returns true if an error occurred, false otherwise.
  1793. bool
  1794. Sema::InstantiateClass(SourceLocation PointOfInstantiation,
  1795. CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
  1796. const MultiLevelTemplateArgumentList &TemplateArgs,
  1797. TemplateSpecializationKind TSK,
  1798. bool Complain) {
  1799. CXXRecordDecl *PatternDef
  1800. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  1801. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
  1802. Instantiation->getInstantiatedFromMemberClass(),
  1803. Pattern, PatternDef, TSK, Complain))
  1804. return true;
  1805. llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
  1806. std::string Name;
  1807. llvm::raw_string_ostream OS(Name);
  1808. Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
  1809. /*Qualified=*/true);
  1810. return Name;
  1811. });
  1812. Pattern = PatternDef;
  1813. // Record the point of instantiation.
  1814. if (MemberSpecializationInfo *MSInfo
  1815. = Instantiation->getMemberSpecializationInfo()) {
  1816. MSInfo->setTemplateSpecializationKind(TSK);
  1817. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1818. } else if (ClassTemplateSpecializationDecl *Spec
  1819. = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
  1820. Spec->setTemplateSpecializationKind(TSK);
  1821. Spec->setPointOfInstantiation(PointOfInstantiation);
  1822. }
  1823. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  1824. if (Inst.isInvalid())
  1825. return true;
  1826. assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
  1827. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  1828. "instantiating class definition");
  1829. // Enter the scope of this instantiation. We don't use
  1830. // PushDeclContext because we don't have a scope.
  1831. ContextRAII SavedContext(*this, Instantiation);
  1832. EnterExpressionEvaluationContext EvalContext(
  1833. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  1834. // If this is an instantiation of a local class, merge this local
  1835. // instantiation scope with the enclosing scope. Otherwise, every
  1836. // instantiation of a class has its own local instantiation scope.
  1837. bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
  1838. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  1839. // Some class state isn't processed immediately but delayed till class
  1840. // instantiation completes. We may not be ready to handle any delayed state
  1841. // already on the stack as it might correspond to a different class, so save
  1842. // it now and put it back later.
  1843. SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
  1844. // Pull attributes from the pattern onto the instantiation.
  1845. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  1846. // Start the definition of this instantiation.
  1847. Instantiation->startDefinition();
  1848. // The instantiation is visible here, even if it was first declared in an
  1849. // unimported module.
  1850. Instantiation->setVisibleDespiteOwningModule();
  1851. // FIXME: This loses the as-written tag kind for an explicit instantiation.
  1852. Instantiation->setTagKind(Pattern->getTagKind());
  1853. // Do substitution on the base class specifiers.
  1854. if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
  1855. Instantiation->setInvalidDecl();
  1856. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  1857. SmallVector<Decl*, 4> Fields;
  1858. // Delay instantiation of late parsed attributes.
  1859. LateInstantiatedAttrVec LateAttrs;
  1860. Instantiator.enableLateAttributeInstantiation(&LateAttrs);
  1861. bool MightHaveConstexprVirtualFunctions = false;
  1862. for (auto *Member : Pattern->decls()) {
  1863. // Don't instantiate members not belonging in this semantic context.
  1864. // e.g. for:
  1865. // @code
  1866. // template <int i> class A {
  1867. // class B *g;
  1868. // };
  1869. // @endcode
  1870. // 'class B' has the template as lexical context but semantically it is
  1871. // introduced in namespace scope.
  1872. if (Member->getDeclContext() != Pattern)
  1873. continue;
  1874. // BlockDecls can appear in a default-member-initializer. They must be the
  1875. // child of a BlockExpr, so we only know how to instantiate them from there.
  1876. if (isa<BlockDecl>(Member))
  1877. continue;
  1878. if (Member->isInvalidDecl()) {
  1879. Instantiation->setInvalidDecl();
  1880. continue;
  1881. }
  1882. Decl *NewMember = Instantiator.Visit(Member);
  1883. if (NewMember) {
  1884. if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
  1885. Fields.push_back(Field);
  1886. } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
  1887. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  1888. // specialization causes the implicit instantiation of the definitions
  1889. // of unscoped member enumerations.
  1890. // Record a point of instantiation for this implicit instantiation.
  1891. if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
  1892. Enum->isCompleteDefinition()) {
  1893. MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
  1894. assert(MSInfo && "no spec info for member enum specialization");
  1895. MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
  1896. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1897. }
  1898. } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
  1899. if (SA->isFailed()) {
  1900. // A static_assert failed. Bail out; instantiating this
  1901. // class is probably not meaningful.
  1902. Instantiation->setInvalidDecl();
  1903. break;
  1904. }
  1905. } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
  1906. if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
  1907. (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
  1908. MightHaveConstexprVirtualFunctions = true;
  1909. }
  1910. if (NewMember->isInvalidDecl())
  1911. Instantiation->setInvalidDecl();
  1912. } else {
  1913. // FIXME: Eventually, a NULL return will mean that one of the
  1914. // instantiations was a semantic disaster, and we'll want to mark the
  1915. // declaration invalid.
  1916. // For now, we expect to skip some members that we can't yet handle.
  1917. }
  1918. }
  1919. // Finish checking fields.
  1920. ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
  1921. SourceLocation(), SourceLocation(), ParsedAttributesView());
  1922. CheckCompletedCXXClass(Instantiation);
  1923. // Default arguments are parsed, if not instantiated. We can go instantiate
  1924. // default arg exprs for default constructors if necessary now.
  1925. ActOnFinishCXXNonNestedClass(Instantiation);
  1926. // Instantiate late parsed attributes, and attach them to their decls.
  1927. // See Sema::InstantiateAttrs
  1928. for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
  1929. E = LateAttrs.end(); I != E; ++I) {
  1930. assert(CurrentInstantiationScope == Instantiator.getStartingScope());
  1931. CurrentInstantiationScope = I->Scope;
  1932. // Allow 'this' within late-parsed attributes.
  1933. NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
  1934. CXXRecordDecl *ThisContext =
  1935. dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
  1936. CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
  1937. ND && ND->isCXXInstanceMember());
  1938. Attr *NewAttr =
  1939. instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
  1940. I->NewDecl->addAttr(NewAttr);
  1941. LocalInstantiationScope::deleteScopes(I->Scope,
  1942. Instantiator.getStartingScope());
  1943. }
  1944. Instantiator.disableLateAttributeInstantiation();
  1945. LateAttrs.clear();
  1946. ActOnFinishDelayedMemberInitializers(Instantiation);
  1947. // FIXME: We should do something similar for explicit instantiations so they
  1948. // end up in the right module.
  1949. if (TSK == TSK_ImplicitInstantiation) {
  1950. Instantiation->setLocation(Pattern->getLocation());
  1951. Instantiation->setLocStart(Pattern->getInnerLocStart());
  1952. Instantiation->setBraceRange(Pattern->getBraceRange());
  1953. }
  1954. if (!Instantiation->isInvalidDecl()) {
  1955. // Perform any dependent diagnostics from the pattern.
  1956. PerformDependentDiagnostics(Pattern, TemplateArgs);
  1957. // Instantiate any out-of-line class template partial
  1958. // specializations now.
  1959. for (TemplateDeclInstantiator::delayed_partial_spec_iterator
  1960. P = Instantiator.delayed_partial_spec_begin(),
  1961. PEnd = Instantiator.delayed_partial_spec_end();
  1962. P != PEnd; ++P) {
  1963. if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
  1964. P->first, P->second)) {
  1965. Instantiation->setInvalidDecl();
  1966. break;
  1967. }
  1968. }
  1969. // Instantiate any out-of-line variable template partial
  1970. // specializations now.
  1971. for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
  1972. P = Instantiator.delayed_var_partial_spec_begin(),
  1973. PEnd = Instantiator.delayed_var_partial_spec_end();
  1974. P != PEnd; ++P) {
  1975. if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
  1976. P->first, P->second)) {
  1977. Instantiation->setInvalidDecl();
  1978. break;
  1979. }
  1980. }
  1981. }
  1982. // Exit the scope of this instantiation.
  1983. SavedContext.pop();
  1984. if (!Instantiation->isInvalidDecl()) {
  1985. Consumer.HandleTagDeclDefinition(Instantiation);
  1986. // Always emit the vtable for an explicit instantiation definition
  1987. // of a polymorphic class template specialization. Otherwise, eagerly
  1988. // instantiate only constexpr virtual functions in preparation for their use
  1989. // in constant evaluation.
  1990. if (TSK == TSK_ExplicitInstantiationDefinition)
  1991. MarkVTableUsed(PointOfInstantiation, Instantiation, true);
  1992. else if (MightHaveConstexprVirtualFunctions)
  1993. MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
  1994. /*ConstexprOnly*/ true);
  1995. }
  1996. return Instantiation->isInvalidDecl();
  1997. }
  1998. /// Instantiate the definition of an enum from a given pattern.
  1999. ///
  2000. /// \param PointOfInstantiation The point of instantiation within the
  2001. /// source code.
  2002. /// \param Instantiation is the declaration whose definition is being
  2003. /// instantiated. This will be a member enumeration of a class
  2004. /// temploid specialization, or a local enumeration within a
  2005. /// function temploid specialization.
  2006. /// \param Pattern The templated declaration from which the instantiation
  2007. /// occurs.
  2008. /// \param TemplateArgs The template arguments to be substituted into
  2009. /// the pattern.
  2010. /// \param TSK The kind of implicit or explicit instantiation to perform.
  2011. ///
  2012. /// \return \c true if an error occurred, \c false otherwise.
  2013. bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
  2014. EnumDecl *Instantiation, EnumDecl *Pattern,
  2015. const MultiLevelTemplateArgumentList &TemplateArgs,
  2016. TemplateSpecializationKind TSK) {
  2017. EnumDecl *PatternDef = Pattern->getDefinition();
  2018. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
  2019. Instantiation->getInstantiatedFromMemberEnum(),
  2020. Pattern, PatternDef, TSK,/*Complain*/true))
  2021. return true;
  2022. Pattern = PatternDef;
  2023. // Record the point of instantiation.
  2024. if (MemberSpecializationInfo *MSInfo
  2025. = Instantiation->getMemberSpecializationInfo()) {
  2026. MSInfo->setTemplateSpecializationKind(TSK);
  2027. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2028. }
  2029. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  2030. if (Inst.isInvalid())
  2031. return true;
  2032. if (Inst.isAlreadyInstantiating())
  2033. return false;
  2034. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  2035. "instantiating enum definition");
  2036. // The instantiation is visible here, even if it was first declared in an
  2037. // unimported module.
  2038. Instantiation->setVisibleDespiteOwningModule();
  2039. // Enter the scope of this instantiation. We don't use
  2040. // PushDeclContext because we don't have a scope.
  2041. ContextRAII SavedContext(*this, Instantiation);
  2042. EnterExpressionEvaluationContext EvalContext(
  2043. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  2044. LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
  2045. // Pull attributes from the pattern onto the instantiation.
  2046. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  2047. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  2048. Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
  2049. // Exit the scope of this instantiation.
  2050. SavedContext.pop();
  2051. return Instantiation->isInvalidDecl();
  2052. }
  2053. /// Instantiate the definition of a field from the given pattern.
  2054. ///
  2055. /// \param PointOfInstantiation The point of instantiation within the
  2056. /// source code.
  2057. /// \param Instantiation is the declaration whose definition is being
  2058. /// instantiated. This will be a class of a class temploid
  2059. /// specialization, or a local enumeration within a function temploid
  2060. /// specialization.
  2061. /// \param Pattern The templated declaration from which the instantiation
  2062. /// occurs.
  2063. /// \param TemplateArgs The template arguments to be substituted into
  2064. /// the pattern.
  2065. ///
  2066. /// \return \c true if an error occurred, \c false otherwise.
  2067. bool Sema::InstantiateInClassInitializer(
  2068. SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
  2069. FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2070. // If there is no initializer, we don't need to do anything.
  2071. if (!Pattern->hasInClassInitializer())
  2072. return false;
  2073. assert(Instantiation->getInClassInitStyle() ==
  2074. Pattern->getInClassInitStyle() &&
  2075. "pattern and instantiation disagree about init style");
  2076. // Error out if we haven't parsed the initializer of the pattern yet because
  2077. // we are waiting for the closing brace of the outer class.
  2078. Expr *OldInit = Pattern->getInClassInitializer();
  2079. if (!OldInit) {
  2080. RecordDecl *PatternRD = Pattern->getParent();
  2081. RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
  2082. Diag(PointOfInstantiation,
  2083. diag::err_in_class_initializer_not_yet_parsed)
  2084. << OutermostClass << Pattern;
  2085. Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
  2086. Instantiation->setInvalidDecl();
  2087. return true;
  2088. }
  2089. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  2090. if (Inst.isInvalid())
  2091. return true;
  2092. if (Inst.isAlreadyInstantiating()) {
  2093. // Error out if we hit an instantiation cycle for this initializer.
  2094. Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
  2095. << Instantiation;
  2096. return true;
  2097. }
  2098. PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
  2099. "instantiating default member init");
  2100. // Enter the scope of this instantiation. We don't use PushDeclContext because
  2101. // we don't have a scope.
  2102. ContextRAII SavedContext(*this, Instantiation->getParent());
  2103. EnterExpressionEvaluationContext EvalContext(
  2104. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  2105. LocalInstantiationScope Scope(*this, true);
  2106. // Instantiate the initializer.
  2107. ActOnStartCXXInClassMemberInitializer();
  2108. CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
  2109. ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
  2110. /*CXXDirectInit=*/false);
  2111. Expr *Init = NewInit.get();
  2112. assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
  2113. ActOnFinishCXXInClassMemberInitializer(
  2114. Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
  2115. if (auto *L = getASTMutationListener())
  2116. L->DefaultMemberInitializerInstantiated(Instantiation);
  2117. // Return true if the in-class initializer is still missing.
  2118. return !Instantiation->getInClassInitializer();
  2119. }
  2120. namespace {
  2121. /// A partial specialization whose template arguments have matched
  2122. /// a given template-id.
  2123. struct PartialSpecMatchResult {
  2124. ClassTemplatePartialSpecializationDecl *Partial;
  2125. TemplateArgumentList *Args;
  2126. };
  2127. }
  2128. bool Sema::usesPartialOrExplicitSpecialization(
  2129. SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
  2130. if (ClassTemplateSpec->getTemplateSpecializationKind() ==
  2131. TSK_ExplicitSpecialization)
  2132. return true;
  2133. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  2134. ClassTemplateSpec->getSpecializedTemplate()
  2135. ->getPartialSpecializations(PartialSpecs);
  2136. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  2137. TemplateDeductionInfo Info(Loc);
  2138. if (!DeduceTemplateArguments(PartialSpecs[I],
  2139. ClassTemplateSpec->getTemplateArgs(), Info))
  2140. return true;
  2141. }
  2142. return false;
  2143. }
  2144. /// Get the instantiation pattern to use to instantiate the definition of a
  2145. /// given ClassTemplateSpecializationDecl (either the pattern of the primary
  2146. /// template or of a partial specialization).
  2147. static CXXRecordDecl *
  2148. getPatternForClassTemplateSpecialization(
  2149. Sema &S, SourceLocation PointOfInstantiation,
  2150. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  2151. TemplateSpecializationKind TSK, bool Complain) {
  2152. Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
  2153. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  2154. return nullptr;
  2155. llvm::PointerUnion<ClassTemplateDecl *,
  2156. ClassTemplatePartialSpecializationDecl *>
  2157. Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
  2158. if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
  2159. // Find best matching specialization.
  2160. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
  2161. // C++ [temp.class.spec.match]p1:
  2162. // When a class template is used in a context that requires an
  2163. // instantiation of the class, it is necessary to determine
  2164. // whether the instantiation is to be generated using the primary
  2165. // template or one of the partial specializations. This is done by
  2166. // matching the template arguments of the class template
  2167. // specialization with the template argument lists of the partial
  2168. // specializations.
  2169. typedef PartialSpecMatchResult MatchResult;
  2170. SmallVector<MatchResult, 4> Matched;
  2171. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  2172. Template->getPartialSpecializations(PartialSpecs);
  2173. TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
  2174. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  2175. ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  2176. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  2177. if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
  2178. Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
  2179. // Store the failed-deduction information for use in diagnostics, later.
  2180. // TODO: Actually use the failed-deduction info?
  2181. FailedCandidates.addCandidate().set(
  2182. DeclAccessPair::make(Template, AS_public), Partial,
  2183. MakeDeductionFailureInfo(S.Context, Result, Info));
  2184. (void)Result;
  2185. } else {
  2186. Matched.push_back(PartialSpecMatchResult());
  2187. Matched.back().Partial = Partial;
  2188. Matched.back().Args = Info.take();
  2189. }
  2190. }
  2191. // If we're dealing with a member template where the template parameters
  2192. // have been instantiated, this provides the original template parameters
  2193. // from which the member template's parameters were instantiated.
  2194. if (Matched.size() >= 1) {
  2195. SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
  2196. if (Matched.size() == 1) {
  2197. // -- If exactly one matching specialization is found, the
  2198. // instantiation is generated from that specialization.
  2199. // We don't need to do anything for this.
  2200. } else {
  2201. // -- If more than one matching specialization is found, the
  2202. // partial order rules (14.5.4.2) are used to determine
  2203. // whether one of the specializations is more specialized
  2204. // than the others. If none of the specializations is more
  2205. // specialized than all of the other matching
  2206. // specializations, then the use of the class template is
  2207. // ambiguous and the program is ill-formed.
  2208. for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
  2209. PEnd = Matched.end();
  2210. P != PEnd; ++P) {
  2211. if (S.getMoreSpecializedPartialSpecialization(
  2212. P->Partial, Best->Partial, PointOfInstantiation) ==
  2213. P->Partial)
  2214. Best = P;
  2215. }
  2216. // Determine if the best partial specialization is more specialized than
  2217. // the others.
  2218. bool Ambiguous = false;
  2219. for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
  2220. PEnd = Matched.end();
  2221. P != PEnd; ++P) {
  2222. if (P != Best && S.getMoreSpecializedPartialSpecialization(
  2223. P->Partial, Best->Partial,
  2224. PointOfInstantiation) != Best->Partial) {
  2225. Ambiguous = true;
  2226. break;
  2227. }
  2228. }
  2229. if (Ambiguous) {
  2230. // Partial ordering did not produce a clear winner. Complain.
  2231. Inst.Clear();
  2232. ClassTemplateSpec->setInvalidDecl();
  2233. S.Diag(PointOfInstantiation,
  2234. diag::err_partial_spec_ordering_ambiguous)
  2235. << ClassTemplateSpec;
  2236. // Print the matching partial specializations.
  2237. for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
  2238. PEnd = Matched.end();
  2239. P != PEnd; ++P)
  2240. S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
  2241. << S.getTemplateArgumentBindingsText(
  2242. P->Partial->getTemplateParameters(), *P->Args);
  2243. return nullptr;
  2244. }
  2245. }
  2246. ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
  2247. } else {
  2248. // -- If no matches are found, the instantiation is generated
  2249. // from the primary template.
  2250. }
  2251. }
  2252. CXXRecordDecl *Pattern = nullptr;
  2253. Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
  2254. if (auto *PartialSpec =
  2255. Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  2256. // Instantiate using the best class template partial specialization.
  2257. while (PartialSpec->getInstantiatedFromMember()) {
  2258. // If we've found an explicit specialization of this class template,
  2259. // stop here and use that as the pattern.
  2260. if (PartialSpec->isMemberSpecialization())
  2261. break;
  2262. PartialSpec = PartialSpec->getInstantiatedFromMember();
  2263. }
  2264. Pattern = PartialSpec;
  2265. } else {
  2266. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
  2267. while (Template->getInstantiatedFromMemberTemplate()) {
  2268. // If we've found an explicit specialization of this class template,
  2269. // stop here and use that as the pattern.
  2270. if (Template->isMemberSpecialization())
  2271. break;
  2272. Template = Template->getInstantiatedFromMemberTemplate();
  2273. }
  2274. Pattern = Template->getTemplatedDecl();
  2275. }
  2276. return Pattern;
  2277. }
  2278. bool Sema::InstantiateClassTemplateSpecialization(
  2279. SourceLocation PointOfInstantiation,
  2280. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  2281. TemplateSpecializationKind TSK, bool Complain) {
  2282. // Perform the actual instantiation on the canonical declaration.
  2283. ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
  2284. ClassTemplateSpec->getCanonicalDecl());
  2285. if (ClassTemplateSpec->isInvalidDecl())
  2286. return true;
  2287. CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
  2288. *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
  2289. if (!Pattern)
  2290. return true;
  2291. return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
  2292. getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
  2293. Complain);
  2294. }
  2295. /// Instantiates the definitions of all of the member
  2296. /// of the given class, which is an instantiation of a class template
  2297. /// or a member class of a template.
  2298. void
  2299. Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
  2300. CXXRecordDecl *Instantiation,
  2301. const MultiLevelTemplateArgumentList &TemplateArgs,
  2302. TemplateSpecializationKind TSK) {
  2303. // FIXME: We need to notify the ASTMutationListener that we did all of these
  2304. // things, in case we have an explicit instantiation definition in a PCM, a
  2305. // module, or preamble, and the declaration is in an imported AST.
  2306. assert(
  2307. (TSK == TSK_ExplicitInstantiationDefinition ||
  2308. TSK == TSK_ExplicitInstantiationDeclaration ||
  2309. (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
  2310. "Unexpected template specialization kind!");
  2311. for (auto *D : Instantiation->decls()) {
  2312. bool SuppressNew = false;
  2313. if (auto *Function = dyn_cast<FunctionDecl>(D)) {
  2314. if (FunctionDecl *Pattern =
  2315. Function->getInstantiatedFromMemberFunction()) {
  2316. if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  2317. continue;
  2318. MemberSpecializationInfo *MSInfo =
  2319. Function->getMemberSpecializationInfo();
  2320. assert(MSInfo && "No member specialization information?");
  2321. if (MSInfo->getTemplateSpecializationKind()
  2322. == TSK_ExplicitSpecialization)
  2323. continue;
  2324. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2325. Function,
  2326. MSInfo->getTemplateSpecializationKind(),
  2327. MSInfo->getPointOfInstantiation(),
  2328. SuppressNew) ||
  2329. SuppressNew)
  2330. continue;
  2331. // C++11 [temp.explicit]p8:
  2332. // An explicit instantiation definition that names a class template
  2333. // specialization explicitly instantiates the class template
  2334. // specialization and is only an explicit instantiation definition
  2335. // of members whose definition is visible at the point of
  2336. // instantiation.
  2337. if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
  2338. continue;
  2339. Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2340. if (Function->isDefined()) {
  2341. // Let the ASTConsumer know that this function has been explicitly
  2342. // instantiated now, and its linkage might have changed.
  2343. Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
  2344. } else if (TSK == TSK_ExplicitInstantiationDefinition) {
  2345. InstantiateFunctionDefinition(PointOfInstantiation, Function);
  2346. } else if (TSK == TSK_ImplicitInstantiation) {
  2347. PendingLocalImplicitInstantiations.push_back(
  2348. std::make_pair(Function, PointOfInstantiation));
  2349. }
  2350. }
  2351. } else if (auto *Var = dyn_cast<VarDecl>(D)) {
  2352. if (isa<VarTemplateSpecializationDecl>(Var))
  2353. continue;
  2354. if (Var->isStaticDataMember()) {
  2355. if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  2356. continue;
  2357. MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
  2358. assert(MSInfo && "No member specialization information?");
  2359. if (MSInfo->getTemplateSpecializationKind()
  2360. == TSK_ExplicitSpecialization)
  2361. continue;
  2362. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2363. Var,
  2364. MSInfo->getTemplateSpecializationKind(),
  2365. MSInfo->getPointOfInstantiation(),
  2366. SuppressNew) ||
  2367. SuppressNew)
  2368. continue;
  2369. if (TSK == TSK_ExplicitInstantiationDefinition) {
  2370. // C++0x [temp.explicit]p8:
  2371. // An explicit instantiation definition that names a class template
  2372. // specialization explicitly instantiates the class template
  2373. // specialization and is only an explicit instantiation definition
  2374. // of members whose definition is visible at the point of
  2375. // instantiation.
  2376. if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
  2377. continue;
  2378. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2379. InstantiateVariableDefinition(PointOfInstantiation, Var);
  2380. } else {
  2381. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2382. }
  2383. }
  2384. } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
  2385. if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  2386. continue;
  2387. // Always skip the injected-class-name, along with any
  2388. // redeclarations of nested classes, since both would cause us
  2389. // to try to instantiate the members of a class twice.
  2390. // Skip closure types; they'll get instantiated when we instantiate
  2391. // the corresponding lambda-expression.
  2392. if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
  2393. Record->isLambda())
  2394. continue;
  2395. MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
  2396. assert(MSInfo && "No member specialization information?");
  2397. if (MSInfo->getTemplateSpecializationKind()
  2398. == TSK_ExplicitSpecialization)
  2399. continue;
  2400. if (Context.getTargetInfo().getTriple().isOSWindows() &&
  2401. TSK == TSK_ExplicitInstantiationDeclaration) {
  2402. // On Windows, explicit instantiation decl of the outer class doesn't
  2403. // affect the inner class. Typically extern template declarations are
  2404. // used in combination with dll import/export annotations, but those
  2405. // are not propagated from the outer class templates to inner classes.
  2406. // Therefore, do not instantiate inner classes on this platform, so
  2407. // that users don't end up with undefined symbols during linking.
  2408. continue;
  2409. }
  2410. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2411. Record,
  2412. MSInfo->getTemplateSpecializationKind(),
  2413. MSInfo->getPointOfInstantiation(),
  2414. SuppressNew) ||
  2415. SuppressNew)
  2416. continue;
  2417. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  2418. assert(Pattern && "Missing instantiated-from-template information");
  2419. if (!Record->getDefinition()) {
  2420. if (!Pattern->getDefinition()) {
  2421. // C++0x [temp.explicit]p8:
  2422. // An explicit instantiation definition that names a class template
  2423. // specialization explicitly instantiates the class template
  2424. // specialization and is only an explicit instantiation definition
  2425. // of members whose definition is visible at the point of
  2426. // instantiation.
  2427. if (TSK == TSK_ExplicitInstantiationDeclaration) {
  2428. MSInfo->setTemplateSpecializationKind(TSK);
  2429. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2430. }
  2431. continue;
  2432. }
  2433. InstantiateClass(PointOfInstantiation, Record, Pattern,
  2434. TemplateArgs,
  2435. TSK);
  2436. } else {
  2437. if (TSK == TSK_ExplicitInstantiationDefinition &&
  2438. Record->getTemplateSpecializationKind() ==
  2439. TSK_ExplicitInstantiationDeclaration) {
  2440. Record->setTemplateSpecializationKind(TSK);
  2441. MarkVTableUsed(PointOfInstantiation, Record, true);
  2442. }
  2443. }
  2444. Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  2445. if (Pattern)
  2446. InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
  2447. TSK);
  2448. } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
  2449. MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
  2450. assert(MSInfo && "No member specialization information?");
  2451. if (MSInfo->getTemplateSpecializationKind()
  2452. == TSK_ExplicitSpecialization)
  2453. continue;
  2454. if (CheckSpecializationInstantiationRedecl(
  2455. PointOfInstantiation, TSK, Enum,
  2456. MSInfo->getTemplateSpecializationKind(),
  2457. MSInfo->getPointOfInstantiation(), SuppressNew) ||
  2458. SuppressNew)
  2459. continue;
  2460. if (Enum->getDefinition())
  2461. continue;
  2462. EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
  2463. assert(Pattern && "Missing instantiated-from-template information");
  2464. if (TSK == TSK_ExplicitInstantiationDefinition) {
  2465. if (!Pattern->getDefinition())
  2466. continue;
  2467. InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
  2468. } else {
  2469. MSInfo->setTemplateSpecializationKind(TSK);
  2470. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2471. }
  2472. } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
  2473. // No need to instantiate in-class initializers during explicit
  2474. // instantiation.
  2475. if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
  2476. CXXRecordDecl *ClassPattern =
  2477. Instantiation->getTemplateInstantiationPattern();
  2478. DeclContext::lookup_result Lookup =
  2479. ClassPattern->lookup(Field->getDeclName());
  2480. FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
  2481. InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
  2482. TemplateArgs);
  2483. }
  2484. }
  2485. }
  2486. }
  2487. /// Instantiate the definitions of all of the members of the
  2488. /// given class template specialization, which was named as part of an
  2489. /// explicit instantiation.
  2490. void
  2491. Sema::InstantiateClassTemplateSpecializationMembers(
  2492. SourceLocation PointOfInstantiation,
  2493. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  2494. TemplateSpecializationKind TSK) {
  2495. // C++0x [temp.explicit]p7:
  2496. // An explicit instantiation that names a class template
  2497. // specialization is an explicit instantion of the same kind
  2498. // (declaration or definition) of each of its members (not
  2499. // including members inherited from base classes) that has not
  2500. // been previously explicitly specialized in the translation unit
  2501. // containing the explicit instantiation, except as described
  2502. // below.
  2503. InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
  2504. getTemplateInstantiationArgs(ClassTemplateSpec),
  2505. TSK);
  2506. }
  2507. StmtResult
  2508. Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2509. if (!S)
  2510. return S;
  2511. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2512. SourceLocation(),
  2513. DeclarationName());
  2514. return Instantiator.TransformStmt(S);
  2515. }
  2516. ExprResult
  2517. Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2518. if (!E)
  2519. return E;
  2520. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2521. SourceLocation(),
  2522. DeclarationName());
  2523. return Instantiator.TransformExpr(E);
  2524. }
  2525. ExprResult Sema::SubstInitializer(Expr *Init,
  2526. const MultiLevelTemplateArgumentList &TemplateArgs,
  2527. bool CXXDirectInit) {
  2528. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2529. SourceLocation(),
  2530. DeclarationName());
  2531. return Instantiator.TransformInitializer(Init, CXXDirectInit);
  2532. }
  2533. bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
  2534. const MultiLevelTemplateArgumentList &TemplateArgs,
  2535. SmallVectorImpl<Expr *> &Outputs) {
  2536. if (Exprs.empty())
  2537. return false;
  2538. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2539. SourceLocation(),
  2540. DeclarationName());
  2541. return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
  2542. IsCall, Outputs);
  2543. }
  2544. NestedNameSpecifierLoc
  2545. Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
  2546. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2547. if (!NNS)
  2548. return NestedNameSpecifierLoc();
  2549. TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
  2550. DeclarationName());
  2551. return Instantiator.TransformNestedNameSpecifierLoc(NNS);
  2552. }
  2553. /// Do template substitution on declaration name info.
  2554. DeclarationNameInfo
  2555. Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
  2556. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2557. TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
  2558. NameInfo.getName());
  2559. return Instantiator.TransformDeclarationNameInfo(NameInfo);
  2560. }
  2561. TemplateName
  2562. Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
  2563. TemplateName Name, SourceLocation Loc,
  2564. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2565. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  2566. DeclarationName());
  2567. CXXScopeSpec SS;
  2568. SS.Adopt(QualifierLoc);
  2569. return Instantiator.TransformTemplateName(SS, Name, Loc);
  2570. }
  2571. bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
  2572. TemplateArgumentListInfo &Result,
  2573. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2574. TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
  2575. DeclarationName());
  2576. return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
  2577. }
  2578. static const Decl *getCanonicalParmVarDecl(const Decl *D) {
  2579. // When storing ParmVarDecls in the local instantiation scope, we always
  2580. // want to use the ParmVarDecl from the canonical function declaration,
  2581. // since the map is then valid for any redeclaration or definition of that
  2582. // function.
  2583. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
  2584. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  2585. unsigned i = PV->getFunctionScopeIndex();
  2586. // This parameter might be from a freestanding function type within the
  2587. // function and isn't necessarily referring to one of FD's parameters.
  2588. if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
  2589. return FD->getCanonicalDecl()->getParamDecl(i);
  2590. }
  2591. }
  2592. return D;
  2593. }
  2594. llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
  2595. LocalInstantiationScope::findInstantiationOf(const Decl *D) {
  2596. D = getCanonicalParmVarDecl(D);
  2597. for (LocalInstantiationScope *Current = this; Current;
  2598. Current = Current->Outer) {
  2599. // Check if we found something within this scope.
  2600. const Decl *CheckD = D;
  2601. do {
  2602. LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
  2603. if (Found != Current->LocalDecls.end())
  2604. return &Found->second;
  2605. // If this is a tag declaration, it's possible that we need to look for
  2606. // a previous declaration.
  2607. if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
  2608. CheckD = Tag->getPreviousDecl();
  2609. else
  2610. CheckD = nullptr;
  2611. } while (CheckD);
  2612. // If we aren't combined with our outer scope, we're done.
  2613. if (!Current->CombineWithOuterScope)
  2614. break;
  2615. }
  2616. // If we're performing a partial substitution during template argument
  2617. // deduction, we may not have values for template parameters yet.
  2618. if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
  2619. isa<TemplateTemplateParmDecl>(D))
  2620. return nullptr;
  2621. // Local types referenced prior to definition may require instantiation.
  2622. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  2623. if (RD->isLocalClass())
  2624. return nullptr;
  2625. // Enumeration types referenced prior to definition may appear as a result of
  2626. // error recovery.
  2627. if (isa<EnumDecl>(D))
  2628. return nullptr;
  2629. // If we didn't find the decl, then we either have a sema bug, or we have a
  2630. // forward reference to a label declaration. Return null to indicate that
  2631. // we have an uninstantiated label.
  2632. assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
  2633. return nullptr;
  2634. }
  2635. void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
  2636. D = getCanonicalParmVarDecl(D);
  2637. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  2638. if (Stored.isNull()) {
  2639. #ifndef NDEBUG
  2640. // It should not be present in any surrounding scope either.
  2641. LocalInstantiationScope *Current = this;
  2642. while (Current->CombineWithOuterScope && Current->Outer) {
  2643. Current = Current->Outer;
  2644. assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
  2645. "Instantiated local in inner and outer scopes");
  2646. }
  2647. #endif
  2648. Stored = Inst;
  2649. } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
  2650. Pack->push_back(cast<VarDecl>(Inst));
  2651. } else {
  2652. assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
  2653. }
  2654. }
  2655. void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
  2656. VarDecl *Inst) {
  2657. D = getCanonicalParmVarDecl(D);
  2658. DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
  2659. Pack->push_back(Inst);
  2660. }
  2661. void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
  2662. #ifndef NDEBUG
  2663. // This should be the first time we've been told about this decl.
  2664. for (LocalInstantiationScope *Current = this;
  2665. Current && Current->CombineWithOuterScope; Current = Current->Outer)
  2666. assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
  2667. "Creating local pack after instantiation of local");
  2668. #endif
  2669. D = getCanonicalParmVarDecl(D);
  2670. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  2671. DeclArgumentPack *Pack = new DeclArgumentPack;
  2672. Stored = Pack;
  2673. ArgumentPacks.push_back(Pack);
  2674. }
  2675. void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
  2676. const TemplateArgument *ExplicitArgs,
  2677. unsigned NumExplicitArgs) {
  2678. assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
  2679. "Already have a partially-substituted pack");
  2680. assert((!PartiallySubstitutedPack
  2681. || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
  2682. "Wrong number of arguments in partially-substituted pack");
  2683. PartiallySubstitutedPack = Pack;
  2684. ArgsInPartiallySubstitutedPack = ExplicitArgs;
  2685. NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
  2686. }
  2687. NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
  2688. const TemplateArgument **ExplicitArgs,
  2689. unsigned *NumExplicitArgs) const {
  2690. if (ExplicitArgs)
  2691. *ExplicitArgs = nullptr;
  2692. if (NumExplicitArgs)
  2693. *NumExplicitArgs = 0;
  2694. for (const LocalInstantiationScope *Current = this; Current;
  2695. Current = Current->Outer) {
  2696. if (Current->PartiallySubstitutedPack) {
  2697. if (ExplicitArgs)
  2698. *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
  2699. if (NumExplicitArgs)
  2700. *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
  2701. return Current->PartiallySubstitutedPack;
  2702. }
  2703. if (!Current->CombineWithOuterScope)
  2704. break;
  2705. }
  2706. return nullptr;
  2707. }