SemaTemplateInstantiateDecl.cpp 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542
  1. //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===/
  8. //
  9. // This file implements C++ template instantiation for declarations.
  10. //
  11. //===----------------------------------------------------------------------===/
  12. #include "clang/Sema/SemaInternal.h"
  13. #include "clang/Sema/Lookup.h"
  14. #include "clang/Sema/PrettyDeclStackTrace.h"
  15. #include "clang/Sema/Template.h"
  16. #include "clang/AST/ASTConsumer.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/DeclVisitor.h"
  20. #include "clang/AST/DependentDiagnostic.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/TypeLoc.h"
  24. #include "clang/Lex/Preprocessor.h"
  25. using namespace clang;
  26. bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
  27. DeclaratorDecl *NewDecl) {
  28. if (!OldDecl->getQualifierLoc())
  29. return false;
  30. NestedNameSpecifierLoc NewQualifierLoc
  31. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  32. TemplateArgs);
  33. if (!NewQualifierLoc)
  34. return true;
  35. NewDecl->setQualifierInfo(NewQualifierLoc);
  36. return false;
  37. }
  38. bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
  39. TagDecl *NewDecl) {
  40. if (!OldDecl->getQualifierLoc())
  41. return false;
  42. NestedNameSpecifierLoc NewQualifierLoc
  43. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  44. TemplateArgs);
  45. if (!NewQualifierLoc)
  46. return true;
  47. NewDecl->setQualifierInfo(NewQualifierLoc);
  48. return false;
  49. }
  50. // Include attribute instantiation code.
  51. #include "clang/Sema/AttrTemplateInstantiate.inc"
  52. void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
  53. const Decl *Tmpl, Decl *New,
  54. LateInstantiatedAttrVec *LateAttrs,
  55. LocalInstantiationScope *OuterMostScope) {
  56. for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
  57. i != e; ++i) {
  58. const Attr *TmplAttr = *i;
  59. // FIXME: This should be generalized to more than just the AlignedAttr.
  60. if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
  61. if (Aligned->isAlignmentDependent()) {
  62. if (Aligned->isAlignmentExpr()) {
  63. // The alignment expression is a constant expression.
  64. EnterExpressionEvaluationContext Unevaluated(*this,
  65. Sema::ConstantEvaluated);
  66. ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
  67. TemplateArgs);
  68. if (!Result.isInvalid())
  69. AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
  70. Aligned->getIsMSDeclSpec());
  71. } else {
  72. TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
  73. TemplateArgs,
  74. Aligned->getLocation(),
  75. DeclarationName());
  76. if (Result)
  77. AddAlignedAttr(Aligned->getLocation(), New, Result,
  78. Aligned->getIsMSDeclSpec());
  79. }
  80. continue;
  81. }
  82. }
  83. if (TmplAttr->isLateParsed() && LateAttrs) {
  84. // Late parsed attributes must be instantiated and attached after the
  85. // enclosing class has been instantiated. See Sema::InstantiateClass.
  86. LocalInstantiationScope *Saved = 0;
  87. if (CurrentInstantiationScope)
  88. Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
  89. LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
  90. } else {
  91. Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
  92. *this, TemplateArgs);
  93. if (NewAttr)
  94. New->addAttr(NewAttr);
  95. }
  96. }
  97. }
  98. Decl *
  99. TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  100. llvm_unreachable("Translation units cannot be instantiated");
  101. }
  102. Decl *
  103. TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
  104. LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  105. D->getIdentifier());
  106. Owner->addDecl(Inst);
  107. return Inst;
  108. }
  109. Decl *
  110. TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
  111. llvm_unreachable("Namespaces cannot be instantiated");
  112. }
  113. Decl *
  114. TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  115. NamespaceAliasDecl *Inst
  116. = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
  117. D->getNamespaceLoc(),
  118. D->getAliasLoc(),
  119. D->getIdentifier(),
  120. D->getQualifierLoc(),
  121. D->getTargetNameLoc(),
  122. D->getNamespace());
  123. Owner->addDecl(Inst);
  124. return Inst;
  125. }
  126. Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
  127. bool IsTypeAlias) {
  128. bool Invalid = false;
  129. TypeSourceInfo *DI = D->getTypeSourceInfo();
  130. if (DI->getType()->isInstantiationDependentType() ||
  131. DI->getType()->isVariablyModifiedType()) {
  132. DI = SemaRef.SubstType(DI, TemplateArgs,
  133. D->getLocation(), D->getDeclName());
  134. if (!DI) {
  135. Invalid = true;
  136. DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
  137. }
  138. } else {
  139. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  140. }
  141. // Create the new typedef
  142. TypedefNameDecl *Typedef;
  143. if (IsTypeAlias)
  144. Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  145. D->getLocation(), D->getIdentifier(), DI);
  146. else
  147. Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  148. D->getLocation(), D->getIdentifier(), DI);
  149. if (Invalid)
  150. Typedef->setInvalidDecl();
  151. // If the old typedef was the name for linkage purposes of an anonymous
  152. // tag decl, re-establish that relationship for the new typedef.
  153. if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
  154. TagDecl *oldTag = oldTagType->getDecl();
  155. if (oldTag->getTypedefNameForAnonDecl() == D) {
  156. TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
  157. assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
  158. newTag->setTypedefNameForAnonDecl(Typedef);
  159. }
  160. }
  161. if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
  162. NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
  163. TemplateArgs);
  164. if (!InstPrev)
  165. return 0;
  166. TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
  167. // If the typedef types are not identical, reject them.
  168. SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
  169. Typedef->setPreviousDeclaration(InstPrevTypedef);
  170. }
  171. SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
  172. Typedef->setAccess(D->getAccess());
  173. return Typedef;
  174. }
  175. Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
  176. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
  177. Owner->addDecl(Typedef);
  178. return Typedef;
  179. }
  180. Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
  181. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
  182. Owner->addDecl(Typedef);
  183. return Typedef;
  184. }
  185. Decl *
  186. TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  187. // Create a local instantiation scope for this type alias template, which
  188. // will contain the instantiations of the template parameters.
  189. LocalInstantiationScope Scope(SemaRef);
  190. TemplateParameterList *TempParams = D->getTemplateParameters();
  191. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  192. if (!InstParams)
  193. return 0;
  194. TypeAliasDecl *Pattern = D->getTemplatedDecl();
  195. TypeAliasTemplateDecl *PrevAliasTemplate = 0;
  196. if (Pattern->getPreviousDecl()) {
  197. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  198. if (Found.first != Found.second) {
  199. PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
  200. }
  201. }
  202. TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
  203. InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
  204. if (!AliasInst)
  205. return 0;
  206. TypeAliasTemplateDecl *Inst
  207. = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  208. D->getDeclName(), InstParams, AliasInst);
  209. if (PrevAliasTemplate)
  210. Inst->setPreviousDeclaration(PrevAliasTemplate);
  211. Inst->setAccess(D->getAccess());
  212. if (!PrevAliasTemplate)
  213. Inst->setInstantiatedFromMemberTemplate(D);
  214. Owner->addDecl(Inst);
  215. return Inst;
  216. }
  217. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
  218. // If this is the variable for an anonymous struct or union,
  219. // instantiate the anonymous struct/union type first.
  220. if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
  221. if (RecordTy->getDecl()->isAnonymousStructOrUnion())
  222. if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
  223. return 0;
  224. // Do substitution on the type of the declaration
  225. TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
  226. TemplateArgs,
  227. D->getTypeSpecStartLoc(),
  228. D->getDeclName());
  229. if (!DI)
  230. return 0;
  231. if (DI->getType()->isFunctionType()) {
  232. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  233. << D->isStaticDataMember() << DI->getType();
  234. return 0;
  235. }
  236. // Build the instantiated declaration
  237. VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
  238. D->getInnerLocStart(),
  239. D->getLocation(), D->getIdentifier(),
  240. DI->getType(), DI,
  241. D->getStorageClass(),
  242. D->getStorageClassAsWritten());
  243. Var->setThreadSpecified(D->isThreadSpecified());
  244. Var->setInitStyle(D->getInitStyle());
  245. Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
  246. Var->setConstexpr(D->isConstexpr());
  247. // Substitute the nested name specifier, if any.
  248. if (SubstQualifier(D, Var))
  249. return 0;
  250. // If we are instantiating a static data member defined
  251. // out-of-line, the instantiation will have the same lexical
  252. // context (which will be a namespace scope) as the template.
  253. if (D->isOutOfLine())
  254. Var->setLexicalDeclContext(D->getLexicalDeclContext());
  255. Var->setAccess(D->getAccess());
  256. if (!D->isStaticDataMember()) {
  257. Var->setUsed(D->isUsed(false));
  258. Var->setReferenced(D->isReferenced());
  259. }
  260. // FIXME: In theory, we could have a previous declaration for variables that
  261. // are not static data members.
  262. // FIXME: having to fake up a LookupResult is dumb.
  263. LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
  264. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  265. if (D->isStaticDataMember())
  266. SemaRef.LookupQualifiedName(Previous, Owner, false);
  267. // In ARC, infer 'retaining' for variables of retainable type.
  268. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  269. SemaRef.inferObjCARCLifetime(Var))
  270. Var->setInvalidDecl();
  271. SemaRef.CheckVariableDeclaration(Var, Previous);
  272. if (D->isOutOfLine()) {
  273. D->getLexicalDeclContext()->addDecl(Var);
  274. Owner->makeDeclVisibleInContext(Var);
  275. } else {
  276. Owner->addDecl(Var);
  277. if (Owner->isFunctionOrMethod())
  278. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
  279. }
  280. SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
  281. // Link instantiations of static data members back to the template from
  282. // which they were instantiated.
  283. if (Var->isStaticDataMember())
  284. SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
  285. TSK_ImplicitInstantiation);
  286. if (Var->getAnyInitializer()) {
  287. // We already have an initializer in the class.
  288. } else if (D->getInit()) {
  289. if (Var->isStaticDataMember() && !D->isOutOfLine())
  290. SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
  291. else
  292. SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
  293. // Instantiate the initializer.
  294. ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
  295. D->getInitStyle() == VarDecl::CallInit);
  296. if (!Init.isInvalid()) {
  297. bool TypeMayContainAuto = true;
  298. if (Init.get()) {
  299. bool DirectInit = D->isDirectInit();
  300. SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
  301. TypeMayContainAuto);
  302. } else
  303. SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
  304. } else {
  305. // FIXME: Not too happy about invalidating the declaration
  306. // because of a bogus initializer.
  307. Var->setInvalidDecl();
  308. }
  309. SemaRef.PopExpressionEvaluationContext();
  310. } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
  311. !Var->isCXXForRangeDecl())
  312. SemaRef.ActOnUninitializedDecl(Var, false);
  313. // Diagnose unused local variables with dependent types, where the diagnostic
  314. // will have been deferred.
  315. if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
  316. D->getType()->isDependentType())
  317. SemaRef.DiagnoseUnusedDecl(Var);
  318. return Var;
  319. }
  320. Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
  321. AccessSpecDecl* AD
  322. = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
  323. D->getAccessSpecifierLoc(), D->getColonLoc());
  324. Owner->addHiddenDecl(AD);
  325. return AD;
  326. }
  327. Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
  328. bool Invalid = false;
  329. TypeSourceInfo *DI = D->getTypeSourceInfo();
  330. if (DI->getType()->isInstantiationDependentType() ||
  331. DI->getType()->isVariablyModifiedType()) {
  332. DI = SemaRef.SubstType(DI, TemplateArgs,
  333. D->getLocation(), D->getDeclName());
  334. if (!DI) {
  335. DI = D->getTypeSourceInfo();
  336. Invalid = true;
  337. } else if (DI->getType()->isFunctionType()) {
  338. // C++ [temp.arg.type]p3:
  339. // If a declaration acquires a function type through a type
  340. // dependent on a template-parameter and this causes a
  341. // declaration that does not use the syntactic form of a
  342. // function declarator to have function type, the program is
  343. // ill-formed.
  344. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  345. << DI->getType();
  346. Invalid = true;
  347. }
  348. } else {
  349. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  350. }
  351. Expr *BitWidth = D->getBitWidth();
  352. if (Invalid)
  353. BitWidth = 0;
  354. else if (BitWidth) {
  355. // The bit-width expression is a constant expression.
  356. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  357. Sema::ConstantEvaluated);
  358. ExprResult InstantiatedBitWidth
  359. = SemaRef.SubstExpr(BitWidth, TemplateArgs);
  360. if (InstantiatedBitWidth.isInvalid()) {
  361. Invalid = true;
  362. BitWidth = 0;
  363. } else
  364. BitWidth = InstantiatedBitWidth.takeAs<Expr>();
  365. }
  366. FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
  367. DI->getType(), DI,
  368. cast<RecordDecl>(Owner),
  369. D->getLocation(),
  370. D->isMutable(),
  371. BitWidth,
  372. D->getInClassInitStyle(),
  373. D->getInnerLocStart(),
  374. D->getAccess(),
  375. 0);
  376. if (!Field) {
  377. cast<Decl>(Owner)->setInvalidDecl();
  378. return 0;
  379. }
  380. SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
  381. if (Invalid)
  382. Field->setInvalidDecl();
  383. if (!Field->getDeclName()) {
  384. // Keep track of where this decl came from.
  385. SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
  386. }
  387. if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
  388. if (Parent->isAnonymousStructOrUnion() &&
  389. Parent->getRedeclContext()->isFunctionOrMethod())
  390. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
  391. }
  392. Field->setImplicit(D->isImplicit());
  393. Field->setAccess(D->getAccess());
  394. Owner->addDecl(Field);
  395. return Field;
  396. }
  397. Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
  398. NamedDecl **NamedChain =
  399. new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
  400. int i = 0;
  401. for (IndirectFieldDecl::chain_iterator PI =
  402. D->chain_begin(), PE = D->chain_end();
  403. PI != PE; ++PI) {
  404. NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
  405. TemplateArgs);
  406. if (!Next)
  407. return 0;
  408. NamedChain[i++] = Next;
  409. }
  410. QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
  411. IndirectFieldDecl* IndirectField
  412. = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  413. D->getIdentifier(), T,
  414. NamedChain, D->getChainingSize());
  415. IndirectField->setImplicit(D->isImplicit());
  416. IndirectField->setAccess(D->getAccess());
  417. Owner->addDecl(IndirectField);
  418. return IndirectField;
  419. }
  420. Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
  421. // Handle friend type expressions by simply substituting template
  422. // parameters into the pattern type and checking the result.
  423. if (TypeSourceInfo *Ty = D->getFriendType()) {
  424. TypeSourceInfo *InstTy;
  425. // If this is an unsupported friend, don't bother substituting template
  426. // arguments into it. The actual type referred to won't be used by any
  427. // parts of Clang, and may not be valid for instantiating. Just use the
  428. // same info for the instantiated friend.
  429. if (D->isUnsupportedFriend()) {
  430. InstTy = Ty;
  431. } else {
  432. InstTy = SemaRef.SubstType(Ty, TemplateArgs,
  433. D->getLocation(), DeclarationName());
  434. }
  435. if (!InstTy)
  436. return 0;
  437. FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
  438. D->getFriendLoc(), InstTy);
  439. if (!FD)
  440. return 0;
  441. FD->setAccess(AS_public);
  442. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  443. Owner->addDecl(FD);
  444. return FD;
  445. }
  446. NamedDecl *ND = D->getFriendDecl();
  447. assert(ND && "friend decl must be a decl or a type!");
  448. // All of the Visit implementations for the various potential friend
  449. // declarations have to be carefully written to work for friend
  450. // objects, with the most important detail being that the target
  451. // decl should almost certainly not be placed in Owner.
  452. Decl *NewND = Visit(ND);
  453. if (!NewND) return 0;
  454. FriendDecl *FD =
  455. FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  456. cast<NamedDecl>(NewND), D->getFriendLoc());
  457. FD->setAccess(AS_public);
  458. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  459. Owner->addDecl(FD);
  460. return FD;
  461. }
  462. Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
  463. Expr *AssertExpr = D->getAssertExpr();
  464. // The expression in a static assertion is a constant expression.
  465. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  466. Sema::ConstantEvaluated);
  467. ExprResult InstantiatedAssertExpr
  468. = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
  469. if (InstantiatedAssertExpr.isInvalid())
  470. return 0;
  471. return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
  472. InstantiatedAssertExpr.get(),
  473. D->getMessage(),
  474. D->getRParenLoc(),
  475. D->isFailed());
  476. }
  477. Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
  478. EnumDecl *PrevDecl = 0;
  479. if (D->getPreviousDecl()) {
  480. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  481. D->getPreviousDecl(),
  482. TemplateArgs);
  483. if (!Prev) return 0;
  484. PrevDecl = cast<EnumDecl>(Prev);
  485. }
  486. EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  487. D->getLocation(), D->getIdentifier(),
  488. PrevDecl, D->isScoped(),
  489. D->isScopedUsingClassTag(), D->isFixed());
  490. if (D->isFixed()) {
  491. if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
  492. // If we have type source information for the underlying type, it means it
  493. // has been explicitly set by the user. Perform substitution on it before
  494. // moving on.
  495. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  496. TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
  497. DeclarationName());
  498. if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
  499. Enum->setIntegerType(SemaRef.Context.IntTy);
  500. else
  501. Enum->setIntegerTypeSourceInfo(NewTI);
  502. } else {
  503. assert(!D->getIntegerType()->isDependentType()
  504. && "Dependent type without type source info");
  505. Enum->setIntegerType(D->getIntegerType());
  506. }
  507. }
  508. SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
  509. Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
  510. Enum->setAccess(D->getAccess());
  511. if (SubstQualifier(D, Enum)) return 0;
  512. Owner->addDecl(Enum);
  513. EnumDecl *Def = D->getDefinition();
  514. if (Def && Def != D) {
  515. // If this is an out-of-line definition of an enum member template, check
  516. // that the underlying types match in the instantiation of both
  517. // declarations.
  518. if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
  519. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  520. QualType DefnUnderlying =
  521. SemaRef.SubstType(TI->getType(), TemplateArgs,
  522. UnderlyingLoc, DeclarationName());
  523. SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
  524. DefnUnderlying, Enum);
  525. }
  526. }
  527. if (D->getDeclContext()->isFunctionOrMethod())
  528. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
  529. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  530. // specialization causes the implicit instantiation of the declarations, but
  531. // not the definitions of scoped member enumerations.
  532. // FIXME: There appears to be no wording for what happens for an enum defined
  533. // within a block scope, but we treat that much like a member template. Only
  534. // instantiate the definition when visiting the definition in that case, since
  535. // we will visit all redeclarations.
  536. if (!Enum->isScoped() && Def &&
  537. (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
  538. InstantiateEnumDefinition(Enum, Def);
  539. return Enum;
  540. }
  541. void TemplateDeclInstantiator::InstantiateEnumDefinition(
  542. EnumDecl *Enum, EnumDecl *Pattern) {
  543. Enum->startDefinition();
  544. // Update the location to refer to the definition.
  545. Enum->setLocation(Pattern->getLocation());
  546. SmallVector<Decl*, 4> Enumerators;
  547. EnumConstantDecl *LastEnumConst = 0;
  548. for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
  549. ECEnd = Pattern->enumerator_end();
  550. EC != ECEnd; ++EC) {
  551. // The specified value for the enumerator.
  552. ExprResult Value = SemaRef.Owned((Expr *)0);
  553. if (Expr *UninstValue = EC->getInitExpr()) {
  554. // The enumerator's value expression is a constant expression.
  555. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  556. Sema::ConstantEvaluated);
  557. Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
  558. }
  559. // Drop the initial value and continue.
  560. bool isInvalid = false;
  561. if (Value.isInvalid()) {
  562. Value = SemaRef.Owned((Expr *)0);
  563. isInvalid = true;
  564. }
  565. EnumConstantDecl *EnumConst
  566. = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
  567. EC->getLocation(), EC->getIdentifier(),
  568. Value.get());
  569. if (isInvalid) {
  570. if (EnumConst)
  571. EnumConst->setInvalidDecl();
  572. Enum->setInvalidDecl();
  573. }
  574. if (EnumConst) {
  575. SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
  576. EnumConst->setAccess(Enum->getAccess());
  577. Enum->addDecl(EnumConst);
  578. Enumerators.push_back(EnumConst);
  579. LastEnumConst = EnumConst;
  580. if (Pattern->getDeclContext()->isFunctionOrMethod() &&
  581. !Enum->isScoped()) {
  582. // If the enumeration is within a function or method, record the enum
  583. // constant as a local.
  584. SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
  585. }
  586. }
  587. }
  588. // FIXME: Fixup LBraceLoc
  589. SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
  590. Enum->getRBraceLoc(), Enum,
  591. Enumerators.data(), Enumerators.size(),
  592. 0, 0);
  593. }
  594. Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
  595. llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
  596. }
  597. Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  598. bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  599. // Create a local instantiation scope for this class template, which
  600. // will contain the instantiations of the template parameters.
  601. LocalInstantiationScope Scope(SemaRef);
  602. TemplateParameterList *TempParams = D->getTemplateParameters();
  603. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  604. if (!InstParams)
  605. return NULL;
  606. CXXRecordDecl *Pattern = D->getTemplatedDecl();
  607. // Instantiate the qualifier. We have to do this first in case
  608. // we're a friend declaration, because if we are then we need to put
  609. // the new declaration in the appropriate context.
  610. NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
  611. if (QualifierLoc) {
  612. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  613. TemplateArgs);
  614. if (!QualifierLoc)
  615. return 0;
  616. }
  617. CXXRecordDecl *PrevDecl = 0;
  618. ClassTemplateDecl *PrevClassTemplate = 0;
  619. if (!isFriend && Pattern->getPreviousDecl()) {
  620. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  621. if (Found.first != Found.second) {
  622. PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
  623. if (PrevClassTemplate)
  624. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  625. }
  626. }
  627. // If this isn't a friend, then it's a member template, in which
  628. // case we just want to build the instantiation in the
  629. // specialization. If it is a friend, we want to build it in
  630. // the appropriate context.
  631. DeclContext *DC = Owner;
  632. if (isFriend) {
  633. if (QualifierLoc) {
  634. CXXScopeSpec SS;
  635. SS.Adopt(QualifierLoc);
  636. DC = SemaRef.computeDeclContext(SS);
  637. if (!DC) return 0;
  638. } else {
  639. DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
  640. Pattern->getDeclContext(),
  641. TemplateArgs);
  642. }
  643. // Look for a previous declaration of the template in the owning
  644. // context.
  645. LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
  646. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  647. SemaRef.LookupQualifiedName(R, DC);
  648. if (R.isSingleResult()) {
  649. PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
  650. if (PrevClassTemplate)
  651. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  652. }
  653. if (!PrevClassTemplate && QualifierLoc) {
  654. SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
  655. << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
  656. << QualifierLoc.getSourceRange();
  657. return 0;
  658. }
  659. bool AdoptedPreviousTemplateParams = false;
  660. if (PrevClassTemplate) {
  661. bool Complain = true;
  662. // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
  663. // template for struct std::tr1::__detail::_Map_base, where the
  664. // template parameters of the friend declaration don't match the
  665. // template parameters of the original declaration. In this one
  666. // case, we don't complain about the ill-formed friend
  667. // declaration.
  668. if (isFriend && Pattern->getIdentifier() &&
  669. Pattern->getIdentifier()->isStr("_Map_base") &&
  670. DC->isNamespace() &&
  671. cast<NamespaceDecl>(DC)->getIdentifier() &&
  672. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
  673. DeclContext *DCParent = DC->getParent();
  674. if (DCParent->isNamespace() &&
  675. cast<NamespaceDecl>(DCParent)->getIdentifier() &&
  676. cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
  677. DeclContext *DCParent2 = DCParent->getParent();
  678. if (DCParent2->isNamespace() &&
  679. cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
  680. cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
  681. DCParent2->getParent()->isTranslationUnit())
  682. Complain = false;
  683. }
  684. }
  685. TemplateParameterList *PrevParams
  686. = PrevClassTemplate->getTemplateParameters();
  687. // Make sure the parameter lists match.
  688. if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
  689. Complain,
  690. Sema::TPL_TemplateMatch)) {
  691. if (Complain)
  692. return 0;
  693. AdoptedPreviousTemplateParams = true;
  694. InstParams = PrevParams;
  695. }
  696. // Do some additional validation, then merge default arguments
  697. // from the existing declarations.
  698. if (!AdoptedPreviousTemplateParams &&
  699. SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
  700. Sema::TPC_ClassTemplate))
  701. return 0;
  702. }
  703. }
  704. CXXRecordDecl *RecordInst
  705. = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
  706. Pattern->getLocStart(), Pattern->getLocation(),
  707. Pattern->getIdentifier(), PrevDecl,
  708. /*DelayTypeCreation=*/true);
  709. if (QualifierLoc)
  710. RecordInst->setQualifierInfo(QualifierLoc);
  711. ClassTemplateDecl *Inst
  712. = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
  713. D->getIdentifier(), InstParams, RecordInst,
  714. PrevClassTemplate);
  715. RecordInst->setDescribedClassTemplate(Inst);
  716. if (isFriend) {
  717. if (PrevClassTemplate)
  718. Inst->setAccess(PrevClassTemplate->getAccess());
  719. else
  720. Inst->setAccess(D->getAccess());
  721. Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
  722. // TODO: do we want to track the instantiation progeny of this
  723. // friend target decl?
  724. } else {
  725. Inst->setAccess(D->getAccess());
  726. if (!PrevClassTemplate)
  727. Inst->setInstantiatedFromMemberTemplate(D);
  728. }
  729. // Trigger creation of the type for the instantiation.
  730. SemaRef.Context.getInjectedClassNameType(RecordInst,
  731. Inst->getInjectedClassNameSpecialization());
  732. // Finish handling of friends.
  733. if (isFriend) {
  734. DC->makeDeclVisibleInContext(Inst);
  735. Inst->setLexicalDeclContext(Owner);
  736. RecordInst->setLexicalDeclContext(Owner);
  737. return Inst;
  738. }
  739. if (D->isOutOfLine()) {
  740. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  741. RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
  742. }
  743. Owner->addDecl(Inst);
  744. if (!PrevClassTemplate) {
  745. // Queue up any out-of-line partial specializations of this member
  746. // class template; the client will force their instantiation once
  747. // the enclosing class has been instantiated.
  748. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  749. D->getPartialSpecializations(PartialSpecs);
  750. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  751. if (PartialSpecs[I]->isOutOfLine())
  752. OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
  753. }
  754. return Inst;
  755. }
  756. Decl *
  757. TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
  758. ClassTemplatePartialSpecializationDecl *D) {
  759. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  760. // Lookup the already-instantiated declaration in the instantiation
  761. // of the class template and return that.
  762. DeclContext::lookup_result Found
  763. = Owner->lookup(ClassTemplate->getDeclName());
  764. if (Found.first == Found.second)
  765. return 0;
  766. ClassTemplateDecl *InstClassTemplate
  767. = dyn_cast<ClassTemplateDecl>(*Found.first);
  768. if (!InstClassTemplate)
  769. return 0;
  770. if (ClassTemplatePartialSpecializationDecl *Result
  771. = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
  772. return Result;
  773. return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
  774. }
  775. Decl *
  776. TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  777. // Create a local instantiation scope for this function template, which
  778. // will contain the instantiations of the template parameters and then get
  779. // merged with the local instantiation scope for the function template
  780. // itself.
  781. LocalInstantiationScope Scope(SemaRef);
  782. TemplateParameterList *TempParams = D->getTemplateParameters();
  783. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  784. if (!InstParams)
  785. return NULL;
  786. FunctionDecl *Instantiated = 0;
  787. if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
  788. Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
  789. InstParams));
  790. else
  791. Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
  792. D->getTemplatedDecl(),
  793. InstParams));
  794. if (!Instantiated)
  795. return 0;
  796. // Link the instantiated function template declaration to the function
  797. // template from which it was instantiated.
  798. FunctionTemplateDecl *InstTemplate
  799. = Instantiated->getDescribedFunctionTemplate();
  800. InstTemplate->setAccess(D->getAccess());
  801. assert(InstTemplate &&
  802. "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
  803. bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
  804. // Link the instantiation back to the pattern *unless* this is a
  805. // non-definition friend declaration.
  806. if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
  807. !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
  808. InstTemplate->setInstantiatedFromMemberTemplate(D);
  809. // Make declarations visible in the appropriate context.
  810. if (!isFriend) {
  811. Owner->addDecl(InstTemplate);
  812. } else if (InstTemplate->getDeclContext()->isRecord() &&
  813. !D->getPreviousDecl()) {
  814. SemaRef.CheckFriendAccess(InstTemplate);
  815. }
  816. return InstTemplate;
  817. }
  818. Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
  819. CXXRecordDecl *PrevDecl = 0;
  820. if (D->isInjectedClassName())
  821. PrevDecl = cast<CXXRecordDecl>(Owner);
  822. else if (D->getPreviousDecl()) {
  823. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  824. D->getPreviousDecl(),
  825. TemplateArgs);
  826. if (!Prev) return 0;
  827. PrevDecl = cast<CXXRecordDecl>(Prev);
  828. }
  829. CXXRecordDecl *Record
  830. = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
  831. D->getLocStart(), D->getLocation(),
  832. D->getIdentifier(), PrevDecl);
  833. // Substitute the nested name specifier, if any.
  834. if (SubstQualifier(D, Record))
  835. return 0;
  836. Record->setImplicit(D->isImplicit());
  837. // FIXME: Check against AS_none is an ugly hack to work around the issue that
  838. // the tag decls introduced by friend class declarations don't have an access
  839. // specifier. Remove once this area of the code gets sorted out.
  840. if (D->getAccess() != AS_none)
  841. Record->setAccess(D->getAccess());
  842. if (!D->isInjectedClassName())
  843. Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  844. // If the original function was part of a friend declaration,
  845. // inherit its namespace state.
  846. if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
  847. Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
  848. // Make sure that anonymous structs and unions are recorded.
  849. if (D->isAnonymousStructOrUnion()) {
  850. Record->setAnonymousStructOrUnion(true);
  851. if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
  852. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
  853. }
  854. Owner->addDecl(Record);
  855. return Record;
  856. }
  857. /// Normal class members are of more specific types and therefore
  858. /// don't make it here. This function serves two purposes:
  859. /// 1) instantiating function templates
  860. /// 2) substituting friend declarations
  861. /// FIXME: preserve function definitions in case #2
  862. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
  863. TemplateParameterList *TemplateParams) {
  864. // Check whether there is already a function template specialization for
  865. // this declaration.
  866. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  867. if (FunctionTemplate && !TemplateParams) {
  868. std::pair<const TemplateArgument *, unsigned> Innermost
  869. = TemplateArgs.getInnermost();
  870. void *InsertPos = 0;
  871. FunctionDecl *SpecFunc
  872. = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
  873. InsertPos);
  874. // If we already have a function template specialization, return it.
  875. if (SpecFunc)
  876. return SpecFunc;
  877. }
  878. bool isFriend;
  879. if (FunctionTemplate)
  880. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  881. else
  882. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  883. bool MergeWithParentScope = (TemplateParams != 0) ||
  884. Owner->isFunctionOrMethod() ||
  885. !(isa<Decl>(Owner) &&
  886. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  887. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  888. SmallVector<ParmVarDecl *, 4> Params;
  889. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  890. if (!TInfo)
  891. return 0;
  892. QualType T = TInfo->getType();
  893. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  894. if (QualifierLoc) {
  895. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  896. TemplateArgs);
  897. if (!QualifierLoc)
  898. return 0;
  899. }
  900. // If we're instantiating a local function declaration, put the result
  901. // in the owner; otherwise we need to find the instantiated context.
  902. DeclContext *DC;
  903. if (D->getDeclContext()->isFunctionOrMethod())
  904. DC = Owner;
  905. else if (isFriend && QualifierLoc) {
  906. CXXScopeSpec SS;
  907. SS.Adopt(QualifierLoc);
  908. DC = SemaRef.computeDeclContext(SS);
  909. if (!DC) return 0;
  910. } else {
  911. DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
  912. TemplateArgs);
  913. }
  914. FunctionDecl *Function =
  915. FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  916. D->getLocation(), D->getDeclName(), T, TInfo,
  917. D->getStorageClass(), D->getStorageClassAsWritten(),
  918. D->isInlineSpecified(), D->hasWrittenPrototype(),
  919. D->isConstexpr());
  920. if (QualifierLoc)
  921. Function->setQualifierInfo(QualifierLoc);
  922. DeclContext *LexicalDC = Owner;
  923. if (!isFriend && D->isOutOfLine()) {
  924. assert(D->getDeclContext()->isFileContext());
  925. LexicalDC = D->getDeclContext();
  926. }
  927. Function->setLexicalDeclContext(LexicalDC);
  928. // Attach the parameters
  929. if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
  930. // Adopt the already-instantiated parameters into our own context.
  931. for (unsigned P = 0; P < Params.size(); ++P)
  932. if (Params[P])
  933. Params[P]->setOwningFunction(Function);
  934. } else {
  935. // Since we were instantiated via a typedef of a function type, create
  936. // new parameters.
  937. const FunctionProtoType *Proto
  938. = Function->getType()->getAs<FunctionProtoType>();
  939. assert(Proto && "No function prototype in template instantiation?");
  940. for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
  941. AE = Proto->arg_type_end(); AI != AE; ++AI) {
  942. ParmVarDecl *Param
  943. = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
  944. *AI);
  945. Param->setScopeInfo(0, Params.size());
  946. Params.push_back(Param);
  947. }
  948. }
  949. Function->setParams(Params);
  950. SourceLocation InstantiateAtPOI;
  951. if (TemplateParams) {
  952. // Our resulting instantiation is actually a function template, since we
  953. // are substituting only the outer template parameters. For example, given
  954. //
  955. // template<typename T>
  956. // struct X {
  957. // template<typename U> friend void f(T, U);
  958. // };
  959. //
  960. // X<int> x;
  961. //
  962. // We are instantiating the friend function template "f" within X<int>,
  963. // which means substituting int for T, but leaving "f" as a friend function
  964. // template.
  965. // Build the function template itself.
  966. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
  967. Function->getLocation(),
  968. Function->getDeclName(),
  969. TemplateParams, Function);
  970. Function->setDescribedFunctionTemplate(FunctionTemplate);
  971. FunctionTemplate->setLexicalDeclContext(LexicalDC);
  972. if (isFriend && D->isThisDeclarationADefinition()) {
  973. // TODO: should we remember this connection regardless of whether
  974. // the friend declaration provided a body?
  975. FunctionTemplate->setInstantiatedFromMemberTemplate(
  976. D->getDescribedFunctionTemplate());
  977. }
  978. } else if (FunctionTemplate) {
  979. // Record this function template specialization.
  980. std::pair<const TemplateArgument *, unsigned> Innermost
  981. = TemplateArgs.getInnermost();
  982. Function->setFunctionTemplateSpecialization(FunctionTemplate,
  983. TemplateArgumentList::CreateCopy(SemaRef.Context,
  984. Innermost.first,
  985. Innermost.second),
  986. /*InsertPos=*/0);
  987. } else if (isFriend) {
  988. // Note, we need this connection even if the friend doesn't have a body.
  989. // Its body may exist but not have been attached yet due to deferred
  990. // parsing.
  991. // FIXME: It might be cleaner to set this when attaching the body to the
  992. // friend function declaration, however that would require finding all the
  993. // instantiations and modifying them.
  994. Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  995. }
  996. if (InitFunctionInstantiation(Function, D))
  997. Function->setInvalidDecl();
  998. bool isExplicitSpecialization = false;
  999. LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
  1000. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  1001. if (DependentFunctionTemplateSpecializationInfo *Info
  1002. = D->getDependentSpecializationInfo()) {
  1003. assert(isFriend && "non-friend has dependent specialization info?");
  1004. // This needs to be set now for future sanity.
  1005. Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
  1006. // Instantiate the explicit template arguments.
  1007. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1008. Info->getRAngleLoc());
  1009. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1010. ExplicitArgs, TemplateArgs))
  1011. return 0;
  1012. // Map the candidate templates to their instantiations.
  1013. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  1014. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1015. Info->getTemplate(I),
  1016. TemplateArgs);
  1017. if (!Temp) return 0;
  1018. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  1019. }
  1020. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1021. &ExplicitArgs,
  1022. Previous))
  1023. Function->setInvalidDecl();
  1024. isExplicitSpecialization = true;
  1025. } else if (TemplateParams || !FunctionTemplate) {
  1026. // Look only into the namespace where the friend would be declared to
  1027. // find a previous declaration. This is the innermost enclosing namespace,
  1028. // as described in ActOnFriendFunctionDecl.
  1029. SemaRef.LookupQualifiedName(Previous, DC);
  1030. // In C++, the previous declaration we find might be a tag type
  1031. // (class or enum). In this case, the new declaration will hide the
  1032. // tag type. Note that this does does not apply if we're declaring a
  1033. // typedef (C++ [dcl.typedef]p4).
  1034. if (Previous.isSingleTagDecl())
  1035. Previous.clear();
  1036. }
  1037. SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
  1038. isExplicitSpecialization);
  1039. NamedDecl *PrincipalDecl = (TemplateParams
  1040. ? cast<NamedDecl>(FunctionTemplate)
  1041. : Function);
  1042. // If the original function was part of a friend declaration,
  1043. // inherit its namespace state and add it to the owner.
  1044. if (isFriend) {
  1045. NamedDecl *PrevDecl;
  1046. if (TemplateParams)
  1047. PrevDecl = FunctionTemplate->getPreviousDecl();
  1048. else
  1049. PrevDecl = Function->getPreviousDecl();
  1050. PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
  1051. DC->makeDeclVisibleInContext(PrincipalDecl);
  1052. bool queuedInstantiation = false;
  1053. // C++98 [temp.friend]p5: When a function is defined in a friend function
  1054. // declaration in a class template, the function is defined at each
  1055. // instantiation of the class template. The function is defined even if it
  1056. // is never used.
  1057. // C++11 [temp.friend]p4: When a function is defined in a friend function
  1058. // declaration in a class template, the function is instantiated when the
  1059. // function is odr-used.
  1060. //
  1061. // If -Wc++98-compat is enabled, we go through the motions of checking for a
  1062. // redefinition, but don't instantiate the function.
  1063. if ((!SemaRef.getLangOpts().CPlusPlus0x ||
  1064. SemaRef.Diags.getDiagnosticLevel(
  1065. diag::warn_cxx98_compat_friend_redefinition,
  1066. Function->getLocation())
  1067. != DiagnosticsEngine::Ignored) &&
  1068. D->isThisDeclarationADefinition()) {
  1069. // Check for a function body.
  1070. const FunctionDecl *Definition = 0;
  1071. if (Function->isDefined(Definition) &&
  1072. Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
  1073. SemaRef.Diag(Function->getLocation(),
  1074. SemaRef.getLangOpts().CPlusPlus0x ?
  1075. diag::warn_cxx98_compat_friend_redefinition :
  1076. diag::err_redefinition) << Function->getDeclName();
  1077. SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
  1078. if (!SemaRef.getLangOpts().CPlusPlus0x)
  1079. Function->setInvalidDecl();
  1080. }
  1081. // Check for redefinitions due to other instantiations of this or
  1082. // a similar friend function.
  1083. else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
  1084. REnd = Function->redecls_end();
  1085. R != REnd; ++R) {
  1086. if (*R == Function)
  1087. continue;
  1088. switch (R->getFriendObjectKind()) {
  1089. case Decl::FOK_None:
  1090. if (!SemaRef.getLangOpts().CPlusPlus0x &&
  1091. !queuedInstantiation && R->isUsed(false)) {
  1092. if (MemberSpecializationInfo *MSInfo
  1093. = Function->getMemberSpecializationInfo()) {
  1094. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  1095. SourceLocation Loc = R->getLocation(); // FIXME
  1096. MSInfo->setPointOfInstantiation(Loc);
  1097. SemaRef.PendingLocalImplicitInstantiations.push_back(
  1098. std::make_pair(Function, Loc));
  1099. queuedInstantiation = true;
  1100. }
  1101. }
  1102. }
  1103. break;
  1104. default:
  1105. if (const FunctionDecl *RPattern
  1106. = R->getTemplateInstantiationPattern())
  1107. if (RPattern->isDefined(RPattern)) {
  1108. SemaRef.Diag(Function->getLocation(),
  1109. SemaRef.getLangOpts().CPlusPlus0x ?
  1110. diag::warn_cxx98_compat_friend_redefinition :
  1111. diag::err_redefinition)
  1112. << Function->getDeclName();
  1113. SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
  1114. if (!SemaRef.getLangOpts().CPlusPlus0x)
  1115. Function->setInvalidDecl();
  1116. break;
  1117. }
  1118. }
  1119. }
  1120. }
  1121. }
  1122. if (Function->isOverloadedOperator() && !DC->isRecord() &&
  1123. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  1124. PrincipalDecl->setNonMemberOperator();
  1125. assert(!D->isDefaulted() && "only methods should be defaulted");
  1126. return Function;
  1127. }
  1128. Decl *
  1129. TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
  1130. TemplateParameterList *TemplateParams,
  1131. bool IsClassScopeSpecialization) {
  1132. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1133. if (FunctionTemplate && !TemplateParams) {
  1134. // We are creating a function template specialization from a function
  1135. // template. Check whether there is already a function template
  1136. // specialization for this particular set of template arguments.
  1137. std::pair<const TemplateArgument *, unsigned> Innermost
  1138. = TemplateArgs.getInnermost();
  1139. void *InsertPos = 0;
  1140. FunctionDecl *SpecFunc
  1141. = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
  1142. InsertPos);
  1143. // If we already have a function template specialization, return it.
  1144. if (SpecFunc)
  1145. return SpecFunc;
  1146. }
  1147. bool isFriend;
  1148. if (FunctionTemplate)
  1149. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1150. else
  1151. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1152. bool MergeWithParentScope = (TemplateParams != 0) ||
  1153. !(isa<Decl>(Owner) &&
  1154. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1155. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1156. // Instantiate enclosing template arguments for friends.
  1157. SmallVector<TemplateParameterList *, 4> TempParamLists;
  1158. unsigned NumTempParamLists = 0;
  1159. if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
  1160. TempParamLists.set_size(NumTempParamLists);
  1161. for (unsigned I = 0; I != NumTempParamLists; ++I) {
  1162. TemplateParameterList *TempParams = D->getTemplateParameterList(I);
  1163. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1164. if (!InstParams)
  1165. return NULL;
  1166. TempParamLists[I] = InstParams;
  1167. }
  1168. }
  1169. SmallVector<ParmVarDecl *, 4> Params;
  1170. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1171. if (!TInfo)
  1172. return 0;
  1173. QualType T = TInfo->getType();
  1174. // \brief If the type of this function, after ignoring parentheses,
  1175. // is not *directly* a function type, then we're instantiating a function
  1176. // that was declared via a typedef, e.g.,
  1177. //
  1178. // typedef int functype(int, int);
  1179. // functype func;
  1180. //
  1181. // In this case, we'll just go instantiate the ParmVarDecls that we
  1182. // synthesized in the method declaration.
  1183. if (!isa<FunctionProtoType>(T.IgnoreParens())) {
  1184. assert(!Params.size() && "Instantiating type could not yield parameters");
  1185. SmallVector<QualType, 4> ParamTypes;
  1186. if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
  1187. D->getNumParams(), TemplateArgs, ParamTypes,
  1188. &Params))
  1189. return 0;
  1190. }
  1191. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1192. if (QualifierLoc) {
  1193. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1194. TemplateArgs);
  1195. if (!QualifierLoc)
  1196. return 0;
  1197. }
  1198. DeclContext *DC = Owner;
  1199. if (isFriend) {
  1200. if (QualifierLoc) {
  1201. CXXScopeSpec SS;
  1202. SS.Adopt(QualifierLoc);
  1203. DC = SemaRef.computeDeclContext(SS);
  1204. if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
  1205. return 0;
  1206. } else {
  1207. DC = SemaRef.FindInstantiatedContext(D->getLocation(),
  1208. D->getDeclContext(),
  1209. TemplateArgs);
  1210. }
  1211. if (!DC) return 0;
  1212. }
  1213. // Build the instantiated method declaration.
  1214. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  1215. CXXMethodDecl *Method = 0;
  1216. SourceLocation StartLoc = D->getInnerLocStart();
  1217. DeclarationNameInfo NameInfo
  1218. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1219. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  1220. Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
  1221. StartLoc, NameInfo, T, TInfo,
  1222. Constructor->isExplicit(),
  1223. Constructor->isInlineSpecified(),
  1224. false, Constructor->isConstexpr());
  1225. } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
  1226. Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
  1227. StartLoc, NameInfo, T, TInfo,
  1228. Destructor->isInlineSpecified(),
  1229. false);
  1230. } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
  1231. Method = CXXConversionDecl::Create(SemaRef.Context, Record,
  1232. StartLoc, NameInfo, T, TInfo,
  1233. Conversion->isInlineSpecified(),
  1234. Conversion->isExplicit(),
  1235. Conversion->isConstexpr(),
  1236. Conversion->getLocEnd());
  1237. } else {
  1238. Method = CXXMethodDecl::Create(SemaRef.Context, Record,
  1239. StartLoc, NameInfo, T, TInfo,
  1240. D->isStatic(),
  1241. D->getStorageClassAsWritten(),
  1242. D->isInlineSpecified(),
  1243. D->isConstexpr(), D->getLocEnd());
  1244. }
  1245. if (QualifierLoc)
  1246. Method->setQualifierInfo(QualifierLoc);
  1247. if (TemplateParams) {
  1248. // Our resulting instantiation is actually a function template, since we
  1249. // are substituting only the outer template parameters. For example, given
  1250. //
  1251. // template<typename T>
  1252. // struct X {
  1253. // template<typename U> void f(T, U);
  1254. // };
  1255. //
  1256. // X<int> x;
  1257. //
  1258. // We are instantiating the member template "f" within X<int>, which means
  1259. // substituting int for T, but leaving "f" as a member function template.
  1260. // Build the function template itself.
  1261. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
  1262. Method->getLocation(),
  1263. Method->getDeclName(),
  1264. TemplateParams, Method);
  1265. if (isFriend) {
  1266. FunctionTemplate->setLexicalDeclContext(Owner);
  1267. FunctionTemplate->setObjectOfFriendDecl(true);
  1268. } else if (D->isOutOfLine())
  1269. FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
  1270. Method->setDescribedFunctionTemplate(FunctionTemplate);
  1271. } else if (FunctionTemplate) {
  1272. // Record this function template specialization.
  1273. std::pair<const TemplateArgument *, unsigned> Innermost
  1274. = TemplateArgs.getInnermost();
  1275. Method->setFunctionTemplateSpecialization(FunctionTemplate,
  1276. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1277. Innermost.first,
  1278. Innermost.second),
  1279. /*InsertPos=*/0);
  1280. } else if (!isFriend) {
  1281. // Record that this is an instantiation of a member function.
  1282. Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1283. }
  1284. // If we are instantiating a member function defined
  1285. // out-of-line, the instantiation will have the same lexical
  1286. // context (which will be a namespace scope) as the template.
  1287. if (isFriend) {
  1288. if (NumTempParamLists)
  1289. Method->setTemplateParameterListsInfo(SemaRef.Context,
  1290. NumTempParamLists,
  1291. TempParamLists.data());
  1292. Method->setLexicalDeclContext(Owner);
  1293. Method->setObjectOfFriendDecl(true);
  1294. } else if (D->isOutOfLine())
  1295. Method->setLexicalDeclContext(D->getLexicalDeclContext());
  1296. // Attach the parameters
  1297. for (unsigned P = 0; P < Params.size(); ++P)
  1298. Params[P]->setOwningFunction(Method);
  1299. Method->setParams(Params);
  1300. if (InitMethodInstantiation(Method, D))
  1301. Method->setInvalidDecl();
  1302. LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
  1303. Sema::ForRedeclaration);
  1304. if (!FunctionTemplate || TemplateParams || isFriend) {
  1305. SemaRef.LookupQualifiedName(Previous, Record);
  1306. // In C++, the previous declaration we find might be a tag type
  1307. // (class or enum). In this case, the new declaration will hide the
  1308. // tag type. Note that this does does not apply if we're declaring a
  1309. // typedef (C++ [dcl.typedef]p4).
  1310. if (Previous.isSingleTagDecl())
  1311. Previous.clear();
  1312. }
  1313. if (!IsClassScopeSpecialization)
  1314. SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
  1315. if (D->isPure())
  1316. SemaRef.CheckPureMethod(Method, SourceRange());
  1317. // Propagate access. For a non-friend declaration, the access is
  1318. // whatever we're propagating from. For a friend, it should be the
  1319. // previous declaration we just found.
  1320. if (isFriend && Method->getPreviousDecl())
  1321. Method->setAccess(Method->getPreviousDecl()->getAccess());
  1322. else
  1323. Method->setAccess(D->getAccess());
  1324. if (FunctionTemplate)
  1325. FunctionTemplate->setAccess(Method->getAccess());
  1326. SemaRef.CheckOverrideControl(Method);
  1327. // If a function is defined as defaulted or deleted, mark it as such now.
  1328. if (D->isDefaulted())
  1329. Method->setDefaulted();
  1330. if (D->isDeletedAsWritten())
  1331. Method->setDeletedAsWritten();
  1332. // If there's a function template, let our caller handle it.
  1333. if (FunctionTemplate) {
  1334. // do nothing
  1335. // Don't hide a (potentially) valid declaration with an invalid one.
  1336. } else if (Method->isInvalidDecl() && !Previous.empty()) {
  1337. // do nothing
  1338. // Otherwise, check access to friends and make them visible.
  1339. } else if (isFriend) {
  1340. // We only need to re-check access for methods which we didn't
  1341. // manage to match during parsing.
  1342. if (!D->getPreviousDecl())
  1343. SemaRef.CheckFriendAccess(Method);
  1344. Record->makeDeclVisibleInContext(Method);
  1345. // Otherwise, add the declaration. We don't need to do this for
  1346. // class-scope specializations because we'll have matched them with
  1347. // the appropriate template.
  1348. } else if (!IsClassScopeSpecialization) {
  1349. Owner->addDecl(Method);
  1350. }
  1351. if (D->isExplicitlyDefaulted()) {
  1352. SemaRef.SetDeclDefaulted(Method, Method->getLocation());
  1353. } else {
  1354. assert(!D->isDefaulted() &&
  1355. "should not implicitly default uninstantiated function");
  1356. }
  1357. return Method;
  1358. }
  1359. Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  1360. return VisitCXXMethodDecl(D);
  1361. }
  1362. Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  1363. return VisitCXXMethodDecl(D);
  1364. }
  1365. Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
  1366. return VisitCXXMethodDecl(D);
  1367. }
  1368. ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
  1369. return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
  1370. llvm::Optional<unsigned>(),
  1371. /*ExpectParameterPack=*/false);
  1372. }
  1373. Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
  1374. TemplateTypeParmDecl *D) {
  1375. // TODO: don't always clone when decls are refcounted.
  1376. assert(D->getTypeForDecl()->isTemplateTypeParmType());
  1377. TemplateTypeParmDecl *Inst =
  1378. TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
  1379. D->getLocStart(), D->getLocation(),
  1380. D->getDepth() - TemplateArgs.getNumLevels(),
  1381. D->getIndex(), D->getIdentifier(),
  1382. D->wasDeclaredWithTypename(),
  1383. D->isParameterPack());
  1384. Inst->setAccess(AS_public);
  1385. if (D->hasDefaultArgument())
  1386. Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
  1387. // Introduce this template parameter's instantiation into the instantiation
  1388. // scope.
  1389. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  1390. return Inst;
  1391. }
  1392. Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
  1393. NonTypeTemplateParmDecl *D) {
  1394. // Substitute into the type of the non-type template parameter.
  1395. TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
  1396. SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
  1397. SmallVector<QualType, 4> ExpandedParameterPackTypes;
  1398. bool IsExpandedParameterPack = false;
  1399. TypeSourceInfo *DI;
  1400. QualType T;
  1401. bool Invalid = false;
  1402. if (D->isExpandedParameterPack()) {
  1403. // The non-type template parameter pack is an already-expanded pack
  1404. // expansion of types. Substitute into each of the expanded types.
  1405. ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
  1406. ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
  1407. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  1408. TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
  1409. TemplateArgs,
  1410. D->getLocation(),
  1411. D->getDeclName());
  1412. if (!NewDI)
  1413. return 0;
  1414. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1415. QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
  1416. D->getLocation());
  1417. if (NewT.isNull())
  1418. return 0;
  1419. ExpandedParameterPackTypes.push_back(NewT);
  1420. }
  1421. IsExpandedParameterPack = true;
  1422. DI = D->getTypeSourceInfo();
  1423. T = DI->getType();
  1424. } else if (isa<PackExpansionTypeLoc>(TL)) {
  1425. // The non-type template parameter pack's type is a pack expansion of types.
  1426. // Determine whether we need to expand this parameter pack into separate
  1427. // types.
  1428. PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
  1429. TypeLoc Pattern = Expansion.getPatternLoc();
  1430. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1431. SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  1432. // Determine whether the set of unexpanded parameter packs can and should
  1433. // be expanded.
  1434. bool Expand = true;
  1435. bool RetainExpansion = false;
  1436. llvm::Optional<unsigned> OrigNumExpansions
  1437. = Expansion.getTypePtr()->getNumExpansions();
  1438. llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
  1439. if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
  1440. Pattern.getSourceRange(),
  1441. Unexpanded,
  1442. TemplateArgs,
  1443. Expand, RetainExpansion,
  1444. NumExpansions))
  1445. return 0;
  1446. if (Expand) {
  1447. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1448. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  1449. TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
  1450. D->getLocation(),
  1451. D->getDeclName());
  1452. if (!NewDI)
  1453. return 0;
  1454. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1455. QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
  1456. NewDI->getType(),
  1457. D->getLocation());
  1458. if (NewT.isNull())
  1459. return 0;
  1460. ExpandedParameterPackTypes.push_back(NewT);
  1461. }
  1462. // Note that we have an expanded parameter pack. The "type" of this
  1463. // expanded parameter pack is the original expansion type, but callers
  1464. // will end up using the expanded parameter pack types for type-checking.
  1465. IsExpandedParameterPack = true;
  1466. DI = D->getTypeSourceInfo();
  1467. T = DI->getType();
  1468. } else {
  1469. // We cannot fully expand the pack expansion now, so substitute into the
  1470. // pattern and create a new pack expansion type.
  1471. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  1472. TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
  1473. D->getLocation(),
  1474. D->getDeclName());
  1475. if (!NewPattern)
  1476. return 0;
  1477. DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
  1478. NumExpansions);
  1479. if (!DI)
  1480. return 0;
  1481. T = DI->getType();
  1482. }
  1483. } else {
  1484. // Simple case: substitution into a parameter that is not a parameter pack.
  1485. DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  1486. D->getLocation(), D->getDeclName());
  1487. if (!DI)
  1488. return 0;
  1489. // Check that this type is acceptable for a non-type template parameter.
  1490. T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
  1491. D->getLocation());
  1492. if (T.isNull()) {
  1493. T = SemaRef.Context.IntTy;
  1494. Invalid = true;
  1495. }
  1496. }
  1497. NonTypeTemplateParmDecl *Param;
  1498. if (IsExpandedParameterPack)
  1499. Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
  1500. D->getInnerLocStart(),
  1501. D->getLocation(),
  1502. D->getDepth() - TemplateArgs.getNumLevels(),
  1503. D->getPosition(),
  1504. D->getIdentifier(), T,
  1505. DI,
  1506. ExpandedParameterPackTypes.data(),
  1507. ExpandedParameterPackTypes.size(),
  1508. ExpandedParameterPackTypesAsWritten.data());
  1509. else
  1510. Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
  1511. D->getInnerLocStart(),
  1512. D->getLocation(),
  1513. D->getDepth() - TemplateArgs.getNumLevels(),
  1514. D->getPosition(),
  1515. D->getIdentifier(), T,
  1516. D->isParameterPack(), DI);
  1517. Param->setAccess(AS_public);
  1518. if (Invalid)
  1519. Param->setInvalidDecl();
  1520. Param->setDefaultArgument(D->getDefaultArgument(), false);
  1521. // Introduce this template parameter's instantiation into the instantiation
  1522. // scope.
  1523. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  1524. return Param;
  1525. }
  1526. Decl *
  1527. TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
  1528. TemplateTemplateParmDecl *D) {
  1529. // Instantiate the template parameter list of the template template parameter.
  1530. TemplateParameterList *TempParams = D->getTemplateParameters();
  1531. TemplateParameterList *InstParams;
  1532. {
  1533. // Perform the actual substitution of template parameters within a new,
  1534. // local instantiation scope.
  1535. LocalInstantiationScope Scope(SemaRef);
  1536. InstParams = SubstTemplateParams(TempParams);
  1537. if (!InstParams)
  1538. return NULL;
  1539. }
  1540. // Build the template template parameter.
  1541. TemplateTemplateParmDecl *Param
  1542. = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  1543. D->getDepth() - TemplateArgs.getNumLevels(),
  1544. D->getPosition(), D->isParameterPack(),
  1545. D->getIdentifier(), InstParams);
  1546. Param->setDefaultArgument(D->getDefaultArgument(), false);
  1547. Param->setAccess(AS_public);
  1548. // Introduce this template parameter's instantiation into the instantiation
  1549. // scope.
  1550. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  1551. return Param;
  1552. }
  1553. Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  1554. // Using directives are never dependent (and never contain any types or
  1555. // expressions), so they require no explicit instantiation work.
  1556. UsingDirectiveDecl *Inst
  1557. = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  1558. D->getNamespaceKeyLocation(),
  1559. D->getQualifierLoc(),
  1560. D->getIdentLocation(),
  1561. D->getNominatedNamespace(),
  1562. D->getCommonAncestor());
  1563. Owner->addDecl(Inst);
  1564. return Inst;
  1565. }
  1566. Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
  1567. // The nested name specifier may be dependent, for example
  1568. // template <typename T> struct t {
  1569. // struct s1 { T f1(); };
  1570. // struct s2 : s1 { using s1::f1; };
  1571. // };
  1572. // template struct t<int>;
  1573. // Here, in using s1::f1, s1 refers to t<T>::s1;
  1574. // we need to substitute for t<int>::s1.
  1575. NestedNameSpecifierLoc QualifierLoc
  1576. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  1577. TemplateArgs);
  1578. if (!QualifierLoc)
  1579. return 0;
  1580. // The name info is non-dependent, so no transformation
  1581. // is required.
  1582. DeclarationNameInfo NameInfo = D->getNameInfo();
  1583. // We only need to do redeclaration lookups if we're in a class
  1584. // scope (in fact, it's not really even possible in non-class
  1585. // scopes).
  1586. bool CheckRedeclaration = Owner->isRecord();
  1587. LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
  1588. Sema::ForRedeclaration);
  1589. UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
  1590. D->getUsingLocation(),
  1591. QualifierLoc,
  1592. NameInfo,
  1593. D->isTypeName());
  1594. CXXScopeSpec SS;
  1595. SS.Adopt(QualifierLoc);
  1596. if (CheckRedeclaration) {
  1597. Prev.setHideTags(false);
  1598. SemaRef.LookupQualifiedName(Prev, Owner);
  1599. // Check for invalid redeclarations.
  1600. if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
  1601. D->isTypeName(), SS,
  1602. D->getLocation(), Prev))
  1603. NewUD->setInvalidDecl();
  1604. }
  1605. if (!NewUD->isInvalidDecl() &&
  1606. SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
  1607. D->getLocation()))
  1608. NewUD->setInvalidDecl();
  1609. SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
  1610. NewUD->setAccess(D->getAccess());
  1611. Owner->addDecl(NewUD);
  1612. // Don't process the shadow decls for an invalid decl.
  1613. if (NewUD->isInvalidDecl())
  1614. return NewUD;
  1615. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
  1616. if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
  1617. NewUD->setInvalidDecl();
  1618. return NewUD;
  1619. }
  1620. bool isFunctionScope = Owner->isFunctionOrMethod();
  1621. // Process the shadow decls.
  1622. for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
  1623. I != E; ++I) {
  1624. UsingShadowDecl *Shadow = *I;
  1625. NamedDecl *InstTarget =
  1626. cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
  1627. Shadow->getLocation(),
  1628. Shadow->getTargetDecl(),
  1629. TemplateArgs));
  1630. if (!InstTarget)
  1631. return 0;
  1632. if (CheckRedeclaration &&
  1633. SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
  1634. continue;
  1635. UsingShadowDecl *InstShadow
  1636. = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
  1637. SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
  1638. if (isFunctionScope)
  1639. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
  1640. }
  1641. return NewUD;
  1642. }
  1643. Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
  1644. // Ignore these; we handle them in bulk when processing the UsingDecl.
  1645. return 0;
  1646. }
  1647. Decl * TemplateDeclInstantiator
  1648. ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
  1649. NestedNameSpecifierLoc QualifierLoc
  1650. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  1651. TemplateArgs);
  1652. if (!QualifierLoc)
  1653. return 0;
  1654. CXXScopeSpec SS;
  1655. SS.Adopt(QualifierLoc);
  1656. // Since NameInfo refers to a typename, it cannot be a C++ special name.
  1657. // Hence, no tranformation is required for it.
  1658. DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
  1659. NamedDecl *UD =
  1660. SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
  1661. D->getUsingLoc(), SS, NameInfo, 0,
  1662. /*instantiation*/ true,
  1663. /*typename*/ true, D->getTypenameLoc());
  1664. if (UD)
  1665. SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
  1666. return UD;
  1667. }
  1668. Decl * TemplateDeclInstantiator
  1669. ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  1670. NestedNameSpecifierLoc QualifierLoc
  1671. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
  1672. if (!QualifierLoc)
  1673. return 0;
  1674. CXXScopeSpec SS;
  1675. SS.Adopt(QualifierLoc);
  1676. DeclarationNameInfo NameInfo
  1677. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1678. NamedDecl *UD =
  1679. SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
  1680. D->getUsingLoc(), SS, NameInfo, 0,
  1681. /*instantiation*/ true,
  1682. /*typename*/ false, SourceLocation());
  1683. if (UD)
  1684. SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
  1685. return UD;
  1686. }
  1687. Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
  1688. ClassScopeFunctionSpecializationDecl *Decl) {
  1689. CXXMethodDecl *OldFD = Decl->getSpecialization();
  1690. CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
  1691. 0, true));
  1692. LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
  1693. Sema::ForRedeclaration);
  1694. TemplateArgumentListInfo TemplateArgs;
  1695. TemplateArgumentListInfo* TemplateArgsPtr = 0;
  1696. if (Decl->hasExplicitTemplateArgs()) {
  1697. TemplateArgs = Decl->templateArgs();
  1698. TemplateArgsPtr = &TemplateArgs;
  1699. }
  1700. SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
  1701. if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
  1702. Previous)) {
  1703. NewFD->setInvalidDecl();
  1704. return NewFD;
  1705. }
  1706. // Associate the specialization with the pattern.
  1707. FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
  1708. assert(Specialization && "Class scope Specialization is null");
  1709. SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
  1710. return NewFD;
  1711. }
  1712. Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
  1713. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1714. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  1715. if (D->isInvalidDecl())
  1716. return 0;
  1717. return Instantiator.Visit(D);
  1718. }
  1719. /// \brief Instantiates a nested template parameter list in the current
  1720. /// instantiation context.
  1721. ///
  1722. /// \param L The parameter list to instantiate
  1723. ///
  1724. /// \returns NULL if there was an error
  1725. TemplateParameterList *
  1726. TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
  1727. // Get errors for all the parameters before bailing out.
  1728. bool Invalid = false;
  1729. unsigned N = L->size();
  1730. typedef SmallVector<NamedDecl *, 8> ParamVector;
  1731. ParamVector Params;
  1732. Params.reserve(N);
  1733. for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
  1734. PI != PE; ++PI) {
  1735. NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
  1736. Params.push_back(D);
  1737. Invalid = Invalid || !D || D->isInvalidDecl();
  1738. }
  1739. // Clean up if we had an error.
  1740. if (Invalid)
  1741. return NULL;
  1742. TemplateParameterList *InstL
  1743. = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
  1744. L->getLAngleLoc(), &Params.front(), N,
  1745. L->getRAngleLoc());
  1746. return InstL;
  1747. }
  1748. /// \brief Instantiate the declaration of a class template partial
  1749. /// specialization.
  1750. ///
  1751. /// \param ClassTemplate the (instantiated) class template that is partially
  1752. // specialized by the instantiation of \p PartialSpec.
  1753. ///
  1754. /// \param PartialSpec the (uninstantiated) class template partial
  1755. /// specialization that we are instantiating.
  1756. ///
  1757. /// \returns The instantiated partial specialization, if successful; otherwise,
  1758. /// NULL to indicate an error.
  1759. ClassTemplatePartialSpecializationDecl *
  1760. TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
  1761. ClassTemplateDecl *ClassTemplate,
  1762. ClassTemplatePartialSpecializationDecl *PartialSpec) {
  1763. // Create a local instantiation scope for this class template partial
  1764. // specialization, which will contain the instantiations of the template
  1765. // parameters.
  1766. LocalInstantiationScope Scope(SemaRef);
  1767. // Substitute into the template parameters of the class template partial
  1768. // specialization.
  1769. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  1770. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1771. if (!InstParams)
  1772. return 0;
  1773. // Substitute into the template arguments of the class template partial
  1774. // specialization.
  1775. TemplateArgumentListInfo InstTemplateArgs; // no angle locations
  1776. if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
  1777. PartialSpec->getNumTemplateArgsAsWritten(),
  1778. InstTemplateArgs, TemplateArgs))
  1779. return 0;
  1780. // Check that the template argument list is well-formed for this
  1781. // class template.
  1782. SmallVector<TemplateArgument, 4> Converted;
  1783. if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
  1784. PartialSpec->getLocation(),
  1785. InstTemplateArgs,
  1786. false,
  1787. Converted))
  1788. return 0;
  1789. // Figure out where to insert this class template partial specialization
  1790. // in the member template's set of class template partial specializations.
  1791. void *InsertPos = 0;
  1792. ClassTemplateSpecializationDecl *PrevDecl
  1793. = ClassTemplate->findPartialSpecialization(Converted.data(),
  1794. Converted.size(), InsertPos);
  1795. // Build the canonical type that describes the converted template
  1796. // arguments of the class template partial specialization.
  1797. QualType CanonType
  1798. = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
  1799. Converted.data(),
  1800. Converted.size());
  1801. // Build the fully-sugared type for this class template
  1802. // specialization as the user wrote in the specialization
  1803. // itself. This means that we'll pretty-print the type retrieved
  1804. // from the specialization's declaration the way that the user
  1805. // actually wrote the specialization, rather than formatting the
  1806. // name based on the "canonical" representation used to store the
  1807. // template arguments in the specialization.
  1808. TypeSourceInfo *WrittenTy
  1809. = SemaRef.Context.getTemplateSpecializationTypeInfo(
  1810. TemplateName(ClassTemplate),
  1811. PartialSpec->getLocation(),
  1812. InstTemplateArgs,
  1813. CanonType);
  1814. if (PrevDecl) {
  1815. // We've already seen a partial specialization with the same template
  1816. // parameters and template arguments. This can happen, for example, when
  1817. // substituting the outer template arguments ends up causing two
  1818. // class template partial specializations of a member class template
  1819. // to have identical forms, e.g.,
  1820. //
  1821. // template<typename T, typename U>
  1822. // struct Outer {
  1823. // template<typename X, typename Y> struct Inner;
  1824. // template<typename Y> struct Inner<T, Y>;
  1825. // template<typename Y> struct Inner<U, Y>;
  1826. // };
  1827. //
  1828. // Outer<int, int> outer; // error: the partial specializations of Inner
  1829. // // have the same signature.
  1830. SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
  1831. << WrittenTy->getType();
  1832. SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
  1833. << SemaRef.Context.getTypeDeclType(PrevDecl);
  1834. return 0;
  1835. }
  1836. // Create the class template partial specialization declaration.
  1837. ClassTemplatePartialSpecializationDecl *InstPartialSpec
  1838. = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
  1839. PartialSpec->getTagKind(),
  1840. Owner,
  1841. PartialSpec->getLocStart(),
  1842. PartialSpec->getLocation(),
  1843. InstParams,
  1844. ClassTemplate,
  1845. Converted.data(),
  1846. Converted.size(),
  1847. InstTemplateArgs,
  1848. CanonType,
  1849. 0,
  1850. ClassTemplate->getNextPartialSpecSequenceNumber());
  1851. // Substitute the nested name specifier, if any.
  1852. if (SubstQualifier(PartialSpec, InstPartialSpec))
  1853. return 0;
  1854. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  1855. InstPartialSpec->setTypeAsWritten(WrittenTy);
  1856. // Add this partial specialization to the set of class template partial
  1857. // specializations.
  1858. ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
  1859. return InstPartialSpec;
  1860. }
  1861. TypeSourceInfo*
  1862. TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
  1863. SmallVectorImpl<ParmVarDecl *> &Params) {
  1864. TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
  1865. assert(OldTInfo && "substituting function without type source info");
  1866. assert(Params.empty() && "parameter vector is non-empty at start");
  1867. CXXRecordDecl *ThisContext = 0;
  1868. unsigned ThisTypeQuals = 0;
  1869. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  1870. ThisContext = Method->getParent();
  1871. ThisTypeQuals = Method->getTypeQualifiers();
  1872. }
  1873. TypeSourceInfo *NewTInfo
  1874. = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
  1875. D->getTypeSpecStartLoc(),
  1876. D->getDeclName(),
  1877. ThisContext, ThisTypeQuals);
  1878. if (!NewTInfo)
  1879. return 0;
  1880. if (NewTInfo != OldTInfo) {
  1881. // Get parameters from the new type info.
  1882. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  1883. if (FunctionProtoTypeLoc *OldProtoLoc
  1884. = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
  1885. TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
  1886. FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
  1887. assert(NewProtoLoc && "Missing prototype?");
  1888. unsigned NewIdx = 0;
  1889. for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
  1890. OldIdx != NumOldParams; ++OldIdx) {
  1891. ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
  1892. LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
  1893. llvm::Optional<unsigned> NumArgumentsInExpansion;
  1894. if (OldParam->isParameterPack())
  1895. NumArgumentsInExpansion =
  1896. SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
  1897. TemplateArgs);
  1898. if (!NumArgumentsInExpansion) {
  1899. // Simple case: normal parameter, or a parameter pack that's
  1900. // instantiated to a (still-dependent) parameter pack.
  1901. ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
  1902. Params.push_back(NewParam);
  1903. Scope->InstantiatedLocal(OldParam, NewParam);
  1904. } else {
  1905. // Parameter pack expansion: make the instantiation an argument pack.
  1906. Scope->MakeInstantiatedLocalArgPack(OldParam);
  1907. for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
  1908. ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
  1909. Params.push_back(NewParam);
  1910. Scope->InstantiatedLocalPackArg(OldParam, NewParam);
  1911. }
  1912. }
  1913. }
  1914. }
  1915. } else {
  1916. // The function type itself was not dependent and therefore no
  1917. // substitution occurred. However, we still need to instantiate
  1918. // the function parameters themselves.
  1919. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  1920. if (FunctionProtoTypeLoc *OldProtoLoc
  1921. = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
  1922. for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
  1923. ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
  1924. if (!Parm)
  1925. return 0;
  1926. Params.push_back(Parm);
  1927. }
  1928. }
  1929. }
  1930. return NewTInfo;
  1931. }
  1932. /// Introduce the instantiated function parameters into the local
  1933. /// instantiation scope, and set the parameter names to those used
  1934. /// in the template.
  1935. static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
  1936. const FunctionDecl *PatternDecl,
  1937. LocalInstantiationScope &Scope,
  1938. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1939. unsigned FParamIdx = 0;
  1940. for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
  1941. const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
  1942. if (!PatternParam->isParameterPack()) {
  1943. // Simple case: not a parameter pack.
  1944. assert(FParamIdx < Function->getNumParams());
  1945. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  1946. FunctionParam->setDeclName(PatternParam->getDeclName());
  1947. Scope.InstantiatedLocal(PatternParam, FunctionParam);
  1948. ++FParamIdx;
  1949. continue;
  1950. }
  1951. // Expand the parameter pack.
  1952. Scope.MakeInstantiatedLocalArgPack(PatternParam);
  1953. llvm::Optional<unsigned> NumArgumentsInExpansion
  1954. = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
  1955. assert(NumArgumentsInExpansion &&
  1956. "should only be called when all template arguments are known");
  1957. for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
  1958. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  1959. FunctionParam->setDeclName(PatternParam->getDeclName());
  1960. Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
  1961. ++FParamIdx;
  1962. }
  1963. }
  1964. }
  1965. static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
  1966. const FunctionProtoType *Proto,
  1967. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1968. assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
  1969. // C++11 [expr.prim.general]p3:
  1970. // If a declaration declares a member function or member function
  1971. // template of a class X, the expression this is a prvalue of type
  1972. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  1973. // and the end of the function-definition, member-declarator, or
  1974. // declarator.
  1975. CXXRecordDecl *ThisContext = 0;
  1976. unsigned ThisTypeQuals = 0;
  1977. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
  1978. ThisContext = Method->getParent();
  1979. ThisTypeQuals = Method->getTypeQualifiers();
  1980. }
  1981. Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
  1982. SemaRef.getLangOpts().CPlusPlus0x);
  1983. // The function has an exception specification or a "noreturn"
  1984. // attribute. Substitute into each of the exception types.
  1985. SmallVector<QualType, 4> Exceptions;
  1986. for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
  1987. // FIXME: Poor location information!
  1988. if (const PackExpansionType *PackExpansion
  1989. = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
  1990. // We have a pack expansion. Instantiate it.
  1991. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1992. SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
  1993. Unexpanded);
  1994. assert(!Unexpanded.empty() &&
  1995. "Pack expansion without parameter packs?");
  1996. bool Expand = false;
  1997. bool RetainExpansion = false;
  1998. llvm::Optional<unsigned> NumExpansions
  1999. = PackExpansion->getNumExpansions();
  2000. if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
  2001. SourceRange(),
  2002. Unexpanded,
  2003. TemplateArgs,
  2004. Expand,
  2005. RetainExpansion,
  2006. NumExpansions))
  2007. break;
  2008. if (!Expand) {
  2009. // We can't expand this pack expansion into separate arguments yet;
  2010. // just substitute into the pattern and create a new pack expansion
  2011. // type.
  2012. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2013. QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
  2014. TemplateArgs,
  2015. New->getLocation(), New->getDeclName());
  2016. if (T.isNull())
  2017. break;
  2018. T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
  2019. Exceptions.push_back(T);
  2020. continue;
  2021. }
  2022. // Substitute into the pack expansion pattern for each template
  2023. bool Invalid = false;
  2024. for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
  2025. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
  2026. QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
  2027. TemplateArgs,
  2028. New->getLocation(), New->getDeclName());
  2029. if (T.isNull()) {
  2030. Invalid = true;
  2031. break;
  2032. }
  2033. Exceptions.push_back(T);
  2034. }
  2035. if (Invalid)
  2036. break;
  2037. continue;
  2038. }
  2039. QualType T
  2040. = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
  2041. New->getLocation(), New->getDeclName());
  2042. if (T.isNull() ||
  2043. SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
  2044. continue;
  2045. Exceptions.push_back(T);
  2046. }
  2047. Expr *NoexceptExpr = 0;
  2048. if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
  2049. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  2050. Sema::ConstantEvaluated);
  2051. ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
  2052. if (E.isUsable())
  2053. E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
  2054. if (E.isUsable()) {
  2055. NoexceptExpr = E.take();
  2056. if (!NoexceptExpr->isTypeDependent() &&
  2057. !NoexceptExpr->isValueDependent())
  2058. NoexceptExpr
  2059. = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
  2060. 0, diag::err_noexcept_needs_constant_expression,
  2061. /*AllowFold*/ false).take();
  2062. }
  2063. }
  2064. // Rebuild the function type
  2065. const FunctionProtoType *NewProto
  2066. = New->getType()->getAs<FunctionProtoType>();
  2067. assert(NewProto && "Template instantiation without function prototype?");
  2068. FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
  2069. EPI.ExceptionSpecType = Proto->getExceptionSpecType();
  2070. EPI.NumExceptions = Exceptions.size();
  2071. EPI.Exceptions = Exceptions.data();
  2072. EPI.NoexceptExpr = NoexceptExpr;
  2073. New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
  2074. NewProto->arg_type_begin(),
  2075. NewProto->getNumArgs(),
  2076. EPI));
  2077. }
  2078. void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
  2079. FunctionDecl *Decl) {
  2080. const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
  2081. if (Proto->getExceptionSpecType() != EST_Uninstantiated)
  2082. return;
  2083. InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
  2084. InstantiatingTemplate::ExceptionSpecification());
  2085. if (Inst) {
  2086. // We hit the instantiation depth limit. Clear the exception specification
  2087. // so that our callers don't have to cope with EST_Uninstantiated.
  2088. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  2089. EPI.ExceptionSpecType = EST_None;
  2090. Decl->setType(Context.getFunctionType(Proto->getResultType(),
  2091. Proto->arg_type_begin(),
  2092. Proto->getNumArgs(),
  2093. EPI));
  2094. return;
  2095. }
  2096. // Enter the scope of this instantiation. We don't use
  2097. // PushDeclContext because we don't have a scope.
  2098. Sema::ContextRAII savedContext(*this, Decl);
  2099. LocalInstantiationScope Scope(*this);
  2100. MultiLevelTemplateArgumentList TemplateArgs =
  2101. getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
  2102. FunctionDecl *Template = Proto->getExceptionSpecTemplate();
  2103. addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
  2104. ::InstantiateExceptionSpec(*this, Decl,
  2105. Template->getType()->castAs<FunctionProtoType>(),
  2106. TemplateArgs);
  2107. }
  2108. /// \brief Initializes the common fields of an instantiation function
  2109. /// declaration (New) from the corresponding fields of its template (Tmpl).
  2110. ///
  2111. /// \returns true if there was an error
  2112. bool
  2113. TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
  2114. FunctionDecl *Tmpl) {
  2115. if (Tmpl->isDeleted())
  2116. New->setDeletedAsWritten();
  2117. // If we are performing substituting explicitly-specified template arguments
  2118. // or deduced template arguments into a function template and we reach this
  2119. // point, we are now past the point where SFINAE applies and have committed
  2120. // to keeping the new function template specialization. We therefore
  2121. // convert the active template instantiation for the function template
  2122. // into a template instantiation for this specific function template
  2123. // specialization, which is not a SFINAE context, so that we diagnose any
  2124. // further errors in the declaration itself.
  2125. typedef Sema::ActiveTemplateInstantiation ActiveInstType;
  2126. ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
  2127. if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
  2128. ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
  2129. if (FunctionTemplateDecl *FunTmpl
  2130. = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
  2131. assert(FunTmpl->getTemplatedDecl() == Tmpl &&
  2132. "Deduction from the wrong function template?");
  2133. (void) FunTmpl;
  2134. ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
  2135. ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
  2136. }
  2137. }
  2138. const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
  2139. assert(Proto && "Function template without prototype?");
  2140. if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
  2141. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  2142. // DR1330: In C++11, defer instantiation of a non-trivial
  2143. // exception specification.
  2144. if (SemaRef.getLangOpts().CPlusPlus0x &&
  2145. EPI.ExceptionSpecType != EST_None &&
  2146. EPI.ExceptionSpecType != EST_DynamicNone &&
  2147. EPI.ExceptionSpecType != EST_BasicNoexcept) {
  2148. FunctionDecl *ExceptionSpecTemplate = Tmpl;
  2149. if (EPI.ExceptionSpecType == EST_Uninstantiated)
  2150. ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
  2151. assert(EPI.ExceptionSpecType != EST_Unevaluated &&
  2152. "instantiating implicitly-declared special member");
  2153. // Mark the function has having an uninstantiated exception specification.
  2154. const FunctionProtoType *NewProto
  2155. = New->getType()->getAs<FunctionProtoType>();
  2156. assert(NewProto && "Template instantiation without function prototype?");
  2157. EPI = NewProto->getExtProtoInfo();
  2158. EPI.ExceptionSpecType = EST_Uninstantiated;
  2159. EPI.ExceptionSpecDecl = New;
  2160. EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
  2161. New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
  2162. NewProto->arg_type_begin(),
  2163. NewProto->getNumArgs(),
  2164. EPI));
  2165. } else {
  2166. ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
  2167. }
  2168. }
  2169. // Get the definition. Leaves the variable unchanged if undefined.
  2170. const FunctionDecl *Definition = Tmpl;
  2171. Tmpl->isDefined(Definition);
  2172. SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
  2173. LateAttrs, StartingScope);
  2174. return false;
  2175. }
  2176. /// \brief Initializes common fields of an instantiated method
  2177. /// declaration (New) from the corresponding fields of its template
  2178. /// (Tmpl).
  2179. ///
  2180. /// \returns true if there was an error
  2181. bool
  2182. TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
  2183. CXXMethodDecl *Tmpl) {
  2184. if (InitFunctionInstantiation(New, Tmpl))
  2185. return true;
  2186. New->setAccess(Tmpl->getAccess());
  2187. if (Tmpl->isVirtualAsWritten())
  2188. New->setVirtualAsWritten(true);
  2189. // FIXME: attributes
  2190. // FIXME: New needs a pointer to Tmpl
  2191. return false;
  2192. }
  2193. /// \brief Instantiate the definition of the given function from its
  2194. /// template.
  2195. ///
  2196. /// \param PointOfInstantiation the point at which the instantiation was
  2197. /// required. Note that this is not precisely a "point of instantiation"
  2198. /// for the function, but it's close.
  2199. ///
  2200. /// \param Function the already-instantiated declaration of a
  2201. /// function template specialization or member function of a class template
  2202. /// specialization.
  2203. ///
  2204. /// \param Recursive if true, recursively instantiates any functions that
  2205. /// are required by this instantiation.
  2206. ///
  2207. /// \param DefinitionRequired if true, then we are performing an explicit
  2208. /// instantiation where the body of the function is required. Complain if
  2209. /// there is no such body.
  2210. void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
  2211. FunctionDecl *Function,
  2212. bool Recursive,
  2213. bool DefinitionRequired) {
  2214. if (Function->isInvalidDecl() || Function->isDefined())
  2215. return;
  2216. // Never instantiate an explicit specialization except if it is a class scope
  2217. // explicit specialization.
  2218. if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  2219. !Function->getClassScopeSpecializationPattern())
  2220. return;
  2221. // Find the function body that we'll be substituting.
  2222. const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
  2223. assert(PatternDecl && "instantiating a non-template");
  2224. Stmt *Pattern = PatternDecl->getBody(PatternDecl);
  2225. assert(PatternDecl && "template definition is not a template");
  2226. if (!Pattern) {
  2227. // Try to find a defaulted definition
  2228. PatternDecl->isDefined(PatternDecl);
  2229. }
  2230. assert(PatternDecl && "template definition is not a template");
  2231. // Postpone late parsed template instantiations.
  2232. if (PatternDecl->isLateTemplateParsed() &&
  2233. !LateTemplateParser) {
  2234. PendingInstantiations.push_back(
  2235. std::make_pair(Function, PointOfInstantiation));
  2236. return;
  2237. }
  2238. // Call the LateTemplateParser callback if there a need to late parse
  2239. // a templated function definition.
  2240. if (!Pattern && PatternDecl->isLateTemplateParsed() &&
  2241. LateTemplateParser) {
  2242. LateTemplateParser(OpaqueParser, PatternDecl);
  2243. Pattern = PatternDecl->getBody(PatternDecl);
  2244. }
  2245. if (!Pattern && !PatternDecl->isDefaulted()) {
  2246. if (DefinitionRequired) {
  2247. if (Function->getPrimaryTemplate())
  2248. Diag(PointOfInstantiation,
  2249. diag::err_explicit_instantiation_undefined_func_template)
  2250. << Function->getPrimaryTemplate();
  2251. else
  2252. Diag(PointOfInstantiation,
  2253. diag::err_explicit_instantiation_undefined_member)
  2254. << 1 << Function->getDeclName() << Function->getDeclContext();
  2255. if (PatternDecl)
  2256. Diag(PatternDecl->getLocation(),
  2257. diag::note_explicit_instantiation_here);
  2258. Function->setInvalidDecl();
  2259. } else if (Function->getTemplateSpecializationKind()
  2260. == TSK_ExplicitInstantiationDefinition) {
  2261. PendingInstantiations.push_back(
  2262. std::make_pair(Function, PointOfInstantiation));
  2263. }
  2264. return;
  2265. }
  2266. // C++0x [temp.explicit]p9:
  2267. // Except for inline functions, other explicit instantiation declarations
  2268. // have the effect of suppressing the implicit instantiation of the entity
  2269. // to which they refer.
  2270. if (Function->getTemplateSpecializationKind()
  2271. == TSK_ExplicitInstantiationDeclaration &&
  2272. !PatternDecl->isInlined())
  2273. return;
  2274. InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
  2275. if (Inst)
  2276. return;
  2277. // Copy the inner loc start from the pattern.
  2278. Function->setInnerLocStart(PatternDecl->getInnerLocStart());
  2279. // If we're performing recursive template instantiation, create our own
  2280. // queue of pending implicit instantiations that we will instantiate later,
  2281. // while we're still within our own instantiation context.
  2282. SmallVector<VTableUse, 16> SavedVTableUses;
  2283. std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
  2284. if (Recursive) {
  2285. VTableUses.swap(SavedVTableUses);
  2286. PendingInstantiations.swap(SavedPendingInstantiations);
  2287. }
  2288. EnterExpressionEvaluationContext EvalContext(*this,
  2289. Sema::PotentiallyEvaluated);
  2290. ActOnStartOfFunctionDef(0, Function);
  2291. // Introduce a new scope where local variable instantiations will be
  2292. // recorded, unless we're actually a member function within a local
  2293. // class, in which case we need to merge our results with the parent
  2294. // scope (of the enclosing function).
  2295. bool MergeWithParentScope = false;
  2296. if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
  2297. MergeWithParentScope = Rec->isLocalClass();
  2298. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  2299. // Enter the scope of this instantiation. We don't use
  2300. // PushDeclContext because we don't have a scope.
  2301. Sema::ContextRAII savedContext(*this, Function);
  2302. MultiLevelTemplateArgumentList TemplateArgs =
  2303. getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
  2304. addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
  2305. TemplateArgs);
  2306. if (PatternDecl->isDefaulted()) {
  2307. ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
  2308. SetDeclDefaulted(Function, PatternDecl->getLocation());
  2309. } else {
  2310. // If this is a constructor, instantiate the member initializers.
  2311. if (const CXXConstructorDecl *Ctor =
  2312. dyn_cast<CXXConstructorDecl>(PatternDecl)) {
  2313. InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
  2314. TemplateArgs);
  2315. }
  2316. // Instantiate the function body.
  2317. StmtResult Body = SubstStmt(Pattern, TemplateArgs);
  2318. if (Body.isInvalid())
  2319. Function->setInvalidDecl();
  2320. ActOnFinishFunctionBody(Function, Body.get(),
  2321. /*IsInstantiation=*/true);
  2322. }
  2323. PerformDependentDiagnostics(PatternDecl, TemplateArgs);
  2324. savedContext.pop();
  2325. DeclGroupRef DG(Function);
  2326. Consumer.HandleTopLevelDecl(DG);
  2327. // This class may have local implicit instantiations that need to be
  2328. // instantiation within this scope.
  2329. PerformPendingInstantiations(/*LocalOnly=*/true);
  2330. Scope.Exit();
  2331. if (Recursive) {
  2332. // Define any pending vtables.
  2333. DefineUsedVTables();
  2334. // Instantiate any pending implicit instantiations found during the
  2335. // instantiation of this template.
  2336. PerformPendingInstantiations();
  2337. // Restore the set of pending vtables.
  2338. assert(VTableUses.empty() &&
  2339. "VTableUses should be empty before it is discarded.");
  2340. VTableUses.swap(SavedVTableUses);
  2341. // Restore the set of pending implicit instantiations.
  2342. assert(PendingInstantiations.empty() &&
  2343. "PendingInstantiations should be empty before it is discarded.");
  2344. PendingInstantiations.swap(SavedPendingInstantiations);
  2345. }
  2346. }
  2347. /// \brief Instantiate the definition of the given variable from its
  2348. /// template.
  2349. ///
  2350. /// \param PointOfInstantiation the point at which the instantiation was
  2351. /// required. Note that this is not precisely a "point of instantiation"
  2352. /// for the function, but it's close.
  2353. ///
  2354. /// \param Var the already-instantiated declaration of a static member
  2355. /// variable of a class template specialization.
  2356. ///
  2357. /// \param Recursive if true, recursively instantiates any functions that
  2358. /// are required by this instantiation.
  2359. ///
  2360. /// \param DefinitionRequired if true, then we are performing an explicit
  2361. /// instantiation where an out-of-line definition of the member variable
  2362. /// is required. Complain if there is no such definition.
  2363. void Sema::InstantiateStaticDataMemberDefinition(
  2364. SourceLocation PointOfInstantiation,
  2365. VarDecl *Var,
  2366. bool Recursive,
  2367. bool DefinitionRequired) {
  2368. if (Var->isInvalidDecl())
  2369. return;
  2370. // Find the out-of-line definition of this static data member.
  2371. VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
  2372. assert(Def && "This data member was not instantiated from a template?");
  2373. assert(Def->isStaticDataMember() && "Not a static data member?");
  2374. Def = Def->getOutOfLineDefinition();
  2375. if (!Def) {
  2376. // We did not find an out-of-line definition of this static data member,
  2377. // so we won't perform any instantiation. Rather, we rely on the user to
  2378. // instantiate this definition (or provide a specialization for it) in
  2379. // another translation unit.
  2380. if (DefinitionRequired) {
  2381. Def = Var->getInstantiatedFromStaticDataMember();
  2382. Diag(PointOfInstantiation,
  2383. diag::err_explicit_instantiation_undefined_member)
  2384. << 2 << Var->getDeclName() << Var->getDeclContext();
  2385. Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
  2386. } else if (Var->getTemplateSpecializationKind()
  2387. == TSK_ExplicitInstantiationDefinition) {
  2388. PendingInstantiations.push_back(
  2389. std::make_pair(Var, PointOfInstantiation));
  2390. }
  2391. return;
  2392. }
  2393. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  2394. // Never instantiate an explicit specialization.
  2395. if (TSK == TSK_ExplicitSpecialization)
  2396. return;
  2397. // C++0x [temp.explicit]p9:
  2398. // Except for inline functions, other explicit instantiation declarations
  2399. // have the effect of suppressing the implicit instantiation of the entity
  2400. // to which they refer.
  2401. if (TSK == TSK_ExplicitInstantiationDeclaration)
  2402. return;
  2403. Consumer.HandleCXXStaticMemberVarInstantiation(Var);
  2404. // If we already have a definition, we're done.
  2405. if (VarDecl *Def = Var->getDefinition()) {
  2406. // We may be explicitly instantiating something we've already implicitly
  2407. // instantiated.
  2408. Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
  2409. PointOfInstantiation);
  2410. return;
  2411. }
  2412. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  2413. if (Inst)
  2414. return;
  2415. // If we're performing recursive template instantiation, create our own
  2416. // queue of pending implicit instantiations that we will instantiate later,
  2417. // while we're still within our own instantiation context.
  2418. SmallVector<VTableUse, 16> SavedVTableUses;
  2419. std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
  2420. if (Recursive) {
  2421. VTableUses.swap(SavedVTableUses);
  2422. PendingInstantiations.swap(SavedPendingInstantiations);
  2423. }
  2424. // Enter the scope of this instantiation. We don't use
  2425. // PushDeclContext because we don't have a scope.
  2426. ContextRAII previousContext(*this, Var->getDeclContext());
  2427. LocalInstantiationScope Local(*this);
  2428. VarDecl *OldVar = Var;
  2429. Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
  2430. getTemplateInstantiationArgs(Var)));
  2431. previousContext.pop();
  2432. if (Var) {
  2433. MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
  2434. assert(MSInfo && "Missing member specialization information?");
  2435. Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
  2436. MSInfo->getPointOfInstantiation());
  2437. DeclGroupRef DG(Var);
  2438. Consumer.HandleTopLevelDecl(DG);
  2439. }
  2440. Local.Exit();
  2441. if (Recursive) {
  2442. // Define any newly required vtables.
  2443. DefineUsedVTables();
  2444. // Instantiate any pending implicit instantiations found during the
  2445. // instantiation of this template.
  2446. PerformPendingInstantiations();
  2447. // Restore the set of pending vtables.
  2448. assert(VTableUses.empty() &&
  2449. "VTableUses should be empty before it is discarded, "
  2450. "while instantiating static data member.");
  2451. VTableUses.swap(SavedVTableUses);
  2452. // Restore the set of pending implicit instantiations.
  2453. assert(PendingInstantiations.empty() &&
  2454. "PendingInstantiations should be empty before it is discarded, "
  2455. "while instantiating static data member.");
  2456. PendingInstantiations.swap(SavedPendingInstantiations);
  2457. }
  2458. }
  2459. void
  2460. Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
  2461. const CXXConstructorDecl *Tmpl,
  2462. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2463. SmallVector<CXXCtorInitializer*, 4> NewInits;
  2464. bool AnyErrors = false;
  2465. // Instantiate all the initializers.
  2466. for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
  2467. InitsEnd = Tmpl->init_end();
  2468. Inits != InitsEnd; ++Inits) {
  2469. CXXCtorInitializer *Init = *Inits;
  2470. // Only instantiate written initializers, let Sema re-construct implicit
  2471. // ones.
  2472. if (!Init->isWritten())
  2473. continue;
  2474. SourceLocation EllipsisLoc;
  2475. if (Init->isPackExpansion()) {
  2476. // This is a pack expansion. We should expand it now.
  2477. TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
  2478. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2479. collectUnexpandedParameterPacks(BaseTL, Unexpanded);
  2480. bool ShouldExpand = false;
  2481. bool RetainExpansion = false;
  2482. llvm::Optional<unsigned> NumExpansions;
  2483. if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
  2484. BaseTL.getSourceRange(),
  2485. Unexpanded,
  2486. TemplateArgs, ShouldExpand,
  2487. RetainExpansion,
  2488. NumExpansions)) {
  2489. AnyErrors = true;
  2490. New->setInvalidDecl();
  2491. continue;
  2492. }
  2493. assert(ShouldExpand && "Partial instantiation of base initializer?");
  2494. // Loop over all of the arguments in the argument pack(s),
  2495. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2496. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  2497. // Instantiate the initializer.
  2498. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  2499. /*CXXDirectInit=*/true);
  2500. if (TempInit.isInvalid()) {
  2501. AnyErrors = true;
  2502. break;
  2503. }
  2504. // Instantiate the base type.
  2505. TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
  2506. TemplateArgs,
  2507. Init->getSourceLocation(),
  2508. New->getDeclName());
  2509. if (!BaseTInfo) {
  2510. AnyErrors = true;
  2511. break;
  2512. }
  2513. // Build the initializer.
  2514. MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
  2515. BaseTInfo, TempInit.take(),
  2516. New->getParent(),
  2517. SourceLocation());
  2518. if (NewInit.isInvalid()) {
  2519. AnyErrors = true;
  2520. break;
  2521. }
  2522. NewInits.push_back(NewInit.get());
  2523. }
  2524. continue;
  2525. }
  2526. // Instantiate the initializer.
  2527. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  2528. /*CXXDirectInit=*/true);
  2529. if (TempInit.isInvalid()) {
  2530. AnyErrors = true;
  2531. continue;
  2532. }
  2533. MemInitResult NewInit;
  2534. if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
  2535. TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
  2536. TemplateArgs,
  2537. Init->getSourceLocation(),
  2538. New->getDeclName());
  2539. if (!TInfo) {
  2540. AnyErrors = true;
  2541. New->setInvalidDecl();
  2542. continue;
  2543. }
  2544. if (Init->isBaseInitializer())
  2545. NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
  2546. New->getParent(), EllipsisLoc);
  2547. else
  2548. NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
  2549. cast<CXXRecordDecl>(CurContext->getParent()));
  2550. } else if (Init->isMemberInitializer()) {
  2551. FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
  2552. Init->getMemberLocation(),
  2553. Init->getMember(),
  2554. TemplateArgs));
  2555. if (!Member) {
  2556. AnyErrors = true;
  2557. New->setInvalidDecl();
  2558. continue;
  2559. }
  2560. NewInit = BuildMemberInitializer(Member, TempInit.take(),
  2561. Init->getSourceLocation());
  2562. } else if (Init->isIndirectMemberInitializer()) {
  2563. IndirectFieldDecl *IndirectMember =
  2564. cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
  2565. Init->getMemberLocation(),
  2566. Init->getIndirectMember(), TemplateArgs));
  2567. if (!IndirectMember) {
  2568. AnyErrors = true;
  2569. New->setInvalidDecl();
  2570. continue;
  2571. }
  2572. NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
  2573. Init->getSourceLocation());
  2574. }
  2575. if (NewInit.isInvalid()) {
  2576. AnyErrors = true;
  2577. New->setInvalidDecl();
  2578. } else {
  2579. NewInits.push_back(NewInit.get());
  2580. }
  2581. }
  2582. // Assign all the initializers to the new constructor.
  2583. ActOnMemInitializers(New,
  2584. /*FIXME: ColonLoc */
  2585. SourceLocation(),
  2586. NewInits.data(), NewInits.size(),
  2587. AnyErrors);
  2588. }
  2589. ExprResult Sema::SubstInitializer(Expr *Init,
  2590. const MultiLevelTemplateArgumentList &TemplateArgs,
  2591. bool CXXDirectInit) {
  2592. // Initializers are instantiated like expressions, except that various outer
  2593. // layers are stripped.
  2594. if (!Init)
  2595. return Owned(Init);
  2596. if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
  2597. Init = ExprTemp->getSubExpr();
  2598. while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
  2599. Init = Binder->getSubExpr();
  2600. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
  2601. Init = ICE->getSubExprAsWritten();
  2602. // If this is a direct-initializer, we take apart CXXConstructExprs.
  2603. // Everything else is passed through.
  2604. CXXConstructExpr *Construct;
  2605. if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
  2606. isa<CXXTemporaryObjectExpr>(Construct))
  2607. return SubstExpr(Init, TemplateArgs);
  2608. ASTOwningVector<Expr*> NewArgs(*this);
  2609. if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
  2610. TemplateArgs, NewArgs))
  2611. return ExprError();
  2612. // Treat an empty initializer like none.
  2613. if (NewArgs.empty())
  2614. return Owned((Expr*)0);
  2615. // Build a ParenListExpr to represent anything else.
  2616. // FIXME: Fake locations!
  2617. SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
  2618. return ActOnParenListExpr(Loc, Loc, NewArgs);
  2619. }
  2620. // TODO: this could be templated if the various decl types used the
  2621. // same method name.
  2622. static bool isInstantiationOf(ClassTemplateDecl *Pattern,
  2623. ClassTemplateDecl *Instance) {
  2624. Pattern = Pattern->getCanonicalDecl();
  2625. do {
  2626. Instance = Instance->getCanonicalDecl();
  2627. if (Pattern == Instance) return true;
  2628. Instance = Instance->getInstantiatedFromMemberTemplate();
  2629. } while (Instance);
  2630. return false;
  2631. }
  2632. static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
  2633. FunctionTemplateDecl *Instance) {
  2634. Pattern = Pattern->getCanonicalDecl();
  2635. do {
  2636. Instance = Instance->getCanonicalDecl();
  2637. if (Pattern == Instance) return true;
  2638. Instance = Instance->getInstantiatedFromMemberTemplate();
  2639. } while (Instance);
  2640. return false;
  2641. }
  2642. static bool
  2643. isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
  2644. ClassTemplatePartialSpecializationDecl *Instance) {
  2645. Pattern
  2646. = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
  2647. do {
  2648. Instance = cast<ClassTemplatePartialSpecializationDecl>(
  2649. Instance->getCanonicalDecl());
  2650. if (Pattern == Instance)
  2651. return true;
  2652. Instance = Instance->getInstantiatedFromMember();
  2653. } while (Instance);
  2654. return false;
  2655. }
  2656. static bool isInstantiationOf(CXXRecordDecl *Pattern,
  2657. CXXRecordDecl *Instance) {
  2658. Pattern = Pattern->getCanonicalDecl();
  2659. do {
  2660. Instance = Instance->getCanonicalDecl();
  2661. if (Pattern == Instance) return true;
  2662. Instance = Instance->getInstantiatedFromMemberClass();
  2663. } while (Instance);
  2664. return false;
  2665. }
  2666. static bool isInstantiationOf(FunctionDecl *Pattern,
  2667. FunctionDecl *Instance) {
  2668. Pattern = Pattern->getCanonicalDecl();
  2669. do {
  2670. Instance = Instance->getCanonicalDecl();
  2671. if (Pattern == Instance) return true;
  2672. Instance = Instance->getInstantiatedFromMemberFunction();
  2673. } while (Instance);
  2674. return false;
  2675. }
  2676. static bool isInstantiationOf(EnumDecl *Pattern,
  2677. EnumDecl *Instance) {
  2678. Pattern = Pattern->getCanonicalDecl();
  2679. do {
  2680. Instance = Instance->getCanonicalDecl();
  2681. if (Pattern == Instance) return true;
  2682. Instance = Instance->getInstantiatedFromMemberEnum();
  2683. } while (Instance);
  2684. return false;
  2685. }
  2686. static bool isInstantiationOf(UsingShadowDecl *Pattern,
  2687. UsingShadowDecl *Instance,
  2688. ASTContext &C) {
  2689. return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
  2690. }
  2691. static bool isInstantiationOf(UsingDecl *Pattern,
  2692. UsingDecl *Instance,
  2693. ASTContext &C) {
  2694. return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
  2695. }
  2696. static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
  2697. UsingDecl *Instance,
  2698. ASTContext &C) {
  2699. return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
  2700. }
  2701. static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
  2702. UsingDecl *Instance,
  2703. ASTContext &C) {
  2704. return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
  2705. }
  2706. static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
  2707. VarDecl *Instance) {
  2708. assert(Instance->isStaticDataMember());
  2709. Pattern = Pattern->getCanonicalDecl();
  2710. do {
  2711. Instance = Instance->getCanonicalDecl();
  2712. if (Pattern == Instance) return true;
  2713. Instance = Instance->getInstantiatedFromStaticDataMember();
  2714. } while (Instance);
  2715. return false;
  2716. }
  2717. // Other is the prospective instantiation
  2718. // D is the prospective pattern
  2719. static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
  2720. if (D->getKind() != Other->getKind()) {
  2721. if (UnresolvedUsingTypenameDecl *UUD
  2722. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  2723. if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
  2724. return isInstantiationOf(UUD, UD, Ctx);
  2725. }
  2726. }
  2727. if (UnresolvedUsingValueDecl *UUD
  2728. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  2729. if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
  2730. return isInstantiationOf(UUD, UD, Ctx);
  2731. }
  2732. }
  2733. return false;
  2734. }
  2735. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
  2736. return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
  2737. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
  2738. return isInstantiationOf(cast<FunctionDecl>(D), Function);
  2739. if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
  2740. return isInstantiationOf(cast<EnumDecl>(D), Enum);
  2741. if (VarDecl *Var = dyn_cast<VarDecl>(Other))
  2742. if (Var->isStaticDataMember())
  2743. return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
  2744. if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
  2745. return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
  2746. if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
  2747. return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
  2748. if (ClassTemplatePartialSpecializationDecl *PartialSpec
  2749. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
  2750. return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
  2751. PartialSpec);
  2752. if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
  2753. if (!Field->getDeclName()) {
  2754. // This is an unnamed field.
  2755. return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
  2756. cast<FieldDecl>(D);
  2757. }
  2758. }
  2759. if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
  2760. return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
  2761. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
  2762. return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
  2763. return D->getDeclName() && isa<NamedDecl>(Other) &&
  2764. D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
  2765. }
  2766. template<typename ForwardIterator>
  2767. static NamedDecl *findInstantiationOf(ASTContext &Ctx,
  2768. NamedDecl *D,
  2769. ForwardIterator first,
  2770. ForwardIterator last) {
  2771. for (; first != last; ++first)
  2772. if (isInstantiationOf(Ctx, D, *first))
  2773. return cast<NamedDecl>(*first);
  2774. return 0;
  2775. }
  2776. /// \brief Finds the instantiation of the given declaration context
  2777. /// within the current instantiation.
  2778. ///
  2779. /// \returns NULL if there was an error
  2780. DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
  2781. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2782. if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
  2783. Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
  2784. return cast_or_null<DeclContext>(ID);
  2785. } else return DC;
  2786. }
  2787. /// \brief Find the instantiation of the given declaration within the
  2788. /// current instantiation.
  2789. ///
  2790. /// This routine is intended to be used when \p D is a declaration
  2791. /// referenced from within a template, that needs to mapped into the
  2792. /// corresponding declaration within an instantiation. For example,
  2793. /// given:
  2794. ///
  2795. /// \code
  2796. /// template<typename T>
  2797. /// struct X {
  2798. /// enum Kind {
  2799. /// KnownValue = sizeof(T)
  2800. /// };
  2801. ///
  2802. /// bool getKind() const { return KnownValue; }
  2803. /// };
  2804. ///
  2805. /// template struct X<int>;
  2806. /// \endcode
  2807. ///
  2808. /// In the instantiation of X<int>::getKind(), we need to map the
  2809. /// EnumConstantDecl for KnownValue (which refers to
  2810. /// X<T>::\<Kind>\::KnownValue) to its instantiation
  2811. /// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
  2812. /// this mapping from within the instantiation of X<int>.
  2813. NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
  2814. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2815. DeclContext *ParentDC = D->getDeclContext();
  2816. if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
  2817. isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
  2818. (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
  2819. (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
  2820. // D is a local of some kind. Look into the map of local
  2821. // declarations to their instantiations.
  2822. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  2823. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
  2824. = CurrentInstantiationScope->findInstantiationOf(D);
  2825. if (Found) {
  2826. if (Decl *FD = Found->dyn_cast<Decl *>())
  2827. return cast<NamedDecl>(FD);
  2828. unsigned PackIdx = ArgumentPackSubstitutionIndex;
  2829. return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
  2830. }
  2831. // If we didn't find the decl, then we must have a label decl that hasn't
  2832. // been found yet. Lazily instantiate it and return it now.
  2833. assert(isa<LabelDecl>(D));
  2834. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  2835. assert(Inst && "Failed to instantiate label??");
  2836. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  2837. return cast<LabelDecl>(Inst);
  2838. }
  2839. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  2840. if (!Record->isDependentContext())
  2841. return D;
  2842. // Determine whether this record is the "templated" declaration describing
  2843. // a class template or class template partial specialization.
  2844. ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
  2845. if (ClassTemplate)
  2846. ClassTemplate = ClassTemplate->getCanonicalDecl();
  2847. else if (ClassTemplatePartialSpecializationDecl *PartialSpec
  2848. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
  2849. ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
  2850. // Walk the current context to find either the record or an instantiation of
  2851. // it.
  2852. DeclContext *DC = CurContext;
  2853. while (!DC->isFileContext()) {
  2854. // If we're performing substitution while we're inside the template
  2855. // definition, we'll find our own context. We're done.
  2856. if (DC->Equals(Record))
  2857. return Record;
  2858. if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
  2859. // Check whether we're in the process of instantiating a class template
  2860. // specialization of the template we're mapping.
  2861. if (ClassTemplateSpecializationDecl *InstSpec
  2862. = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
  2863. ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
  2864. if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
  2865. return InstRecord;
  2866. }
  2867. // Check whether we're in the process of instantiating a member class.
  2868. if (isInstantiationOf(Record, InstRecord))
  2869. return InstRecord;
  2870. }
  2871. // Move to the outer template scope.
  2872. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
  2873. if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
  2874. DC = FD->getLexicalDeclContext();
  2875. continue;
  2876. }
  2877. }
  2878. DC = DC->getParent();
  2879. }
  2880. // Fall through to deal with other dependent record types (e.g.,
  2881. // anonymous unions in class templates).
  2882. }
  2883. if (!ParentDC->isDependentContext())
  2884. return D;
  2885. ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
  2886. if (!ParentDC)
  2887. return 0;
  2888. if (ParentDC != D->getDeclContext()) {
  2889. // We performed some kind of instantiation in the parent context,
  2890. // so now we need to look into the instantiated parent context to
  2891. // find the instantiation of the declaration D.
  2892. // If our context used to be dependent, we may need to instantiate
  2893. // it before performing lookup into that context.
  2894. bool IsBeingInstantiated = false;
  2895. if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
  2896. if (!Spec->isDependentContext()) {
  2897. QualType T = Context.getTypeDeclType(Spec);
  2898. const RecordType *Tag = T->getAs<RecordType>();
  2899. assert(Tag && "type of non-dependent record is not a RecordType");
  2900. if (Tag->isBeingDefined())
  2901. IsBeingInstantiated = true;
  2902. if (!Tag->isBeingDefined() &&
  2903. RequireCompleteType(Loc, T, diag::err_incomplete_type))
  2904. return 0;
  2905. ParentDC = Tag->getDecl();
  2906. }
  2907. }
  2908. NamedDecl *Result = 0;
  2909. if (D->getDeclName()) {
  2910. DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
  2911. Result = findInstantiationOf(Context, D, Found.first, Found.second);
  2912. } else {
  2913. // Since we don't have a name for the entity we're looking for,
  2914. // our only option is to walk through all of the declarations to
  2915. // find that name. This will occur in a few cases:
  2916. //
  2917. // - anonymous struct/union within a template
  2918. // - unnamed class/struct/union/enum within a template
  2919. //
  2920. // FIXME: Find a better way to find these instantiations!
  2921. Result = findInstantiationOf(Context, D,
  2922. ParentDC->decls_begin(),
  2923. ParentDC->decls_end());
  2924. }
  2925. if (!Result) {
  2926. if (isa<UsingShadowDecl>(D)) {
  2927. // UsingShadowDecls can instantiate to nothing because of using hiding.
  2928. } else if (Diags.hasErrorOccurred()) {
  2929. // We've already complained about something, so most likely this
  2930. // declaration failed to instantiate. There's no point in complaining
  2931. // further, since this is normal in invalid code.
  2932. } else if (IsBeingInstantiated) {
  2933. // The class in which this member exists is currently being
  2934. // instantiated, and we haven't gotten around to instantiating this
  2935. // member yet. This can happen when the code uses forward declarations
  2936. // of member classes, and introduces ordering dependencies via
  2937. // template instantiation.
  2938. Diag(Loc, diag::err_member_not_yet_instantiated)
  2939. << D->getDeclName()
  2940. << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
  2941. Diag(D->getLocation(), diag::note_non_instantiated_member_here);
  2942. } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  2943. // This enumeration constant was found when the template was defined,
  2944. // but can't be found in the instantiation. This can happen if an
  2945. // unscoped enumeration member is explicitly specialized.
  2946. EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
  2947. EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
  2948. TemplateArgs));
  2949. assert(Spec->getTemplateSpecializationKind() ==
  2950. TSK_ExplicitSpecialization);
  2951. Diag(Loc, diag::err_enumerator_does_not_exist)
  2952. << D->getDeclName()
  2953. << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
  2954. Diag(Spec->getLocation(), diag::note_enum_specialized_here)
  2955. << Context.getTypeDeclType(Spec);
  2956. } else {
  2957. // We should have found something, but didn't.
  2958. llvm_unreachable("Unable to find instantiation of declaration!");
  2959. }
  2960. }
  2961. D = Result;
  2962. }
  2963. return D;
  2964. }
  2965. /// \brief Performs template instantiation for all implicit template
  2966. /// instantiations we have seen until this point.
  2967. void Sema::PerformPendingInstantiations(bool LocalOnly) {
  2968. // Load pending instantiations from the external source.
  2969. if (!LocalOnly && ExternalSource) {
  2970. SmallVector<PendingImplicitInstantiation, 4> Pending;
  2971. ExternalSource->ReadPendingInstantiations(Pending);
  2972. PendingInstantiations.insert(PendingInstantiations.begin(),
  2973. Pending.begin(), Pending.end());
  2974. }
  2975. while (!PendingLocalImplicitInstantiations.empty() ||
  2976. (!LocalOnly && !PendingInstantiations.empty())) {
  2977. PendingImplicitInstantiation Inst;
  2978. if (PendingLocalImplicitInstantiations.empty()) {
  2979. Inst = PendingInstantiations.front();
  2980. PendingInstantiations.pop_front();
  2981. } else {
  2982. Inst = PendingLocalImplicitInstantiations.front();
  2983. PendingLocalImplicitInstantiations.pop_front();
  2984. }
  2985. // Instantiate function definitions
  2986. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
  2987. PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
  2988. "instantiating function definition");
  2989. bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
  2990. TSK_ExplicitInstantiationDefinition;
  2991. InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
  2992. DefinitionRequired);
  2993. continue;
  2994. }
  2995. // Instantiate static data member definitions.
  2996. VarDecl *Var = cast<VarDecl>(Inst.first);
  2997. assert(Var->isStaticDataMember() && "Not a static data member?");
  2998. // Don't try to instantiate declarations if the most recent redeclaration
  2999. // is invalid.
  3000. if (Var->getMostRecentDecl()->isInvalidDecl())
  3001. continue;
  3002. // Check if the most recent declaration has changed the specialization kind
  3003. // and removed the need for implicit instantiation.
  3004. switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
  3005. case TSK_Undeclared:
  3006. llvm_unreachable("Cannot instantitiate an undeclared specialization.");
  3007. case TSK_ExplicitInstantiationDeclaration:
  3008. case TSK_ExplicitSpecialization:
  3009. continue; // No longer need to instantiate this type.
  3010. case TSK_ExplicitInstantiationDefinition:
  3011. // We only need an instantiation if the pending instantiation *is* the
  3012. // explicit instantiation.
  3013. if (Var != Var->getMostRecentDecl()) continue;
  3014. case TSK_ImplicitInstantiation:
  3015. break;
  3016. }
  3017. PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
  3018. "instantiating static data member "
  3019. "definition");
  3020. bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
  3021. TSK_ExplicitInstantiationDefinition;
  3022. InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
  3023. DefinitionRequired);
  3024. }
  3025. }
  3026. void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
  3027. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3028. for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
  3029. E = Pattern->ddiag_end(); I != E; ++I) {
  3030. DependentDiagnostic *DD = *I;
  3031. switch (DD->getKind()) {
  3032. case DependentDiagnostic::Access:
  3033. HandleDependentAccessCheck(*DD, TemplateArgs);
  3034. break;
  3035. }
  3036. }
  3037. }