SemaLookup.cpp 193 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218
  1. //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements name lookup for C, C++, Objective-C, and
  10. // Objective-C++.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/CXXInheritance.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclLookups.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/Basic/Builtins.h"
  23. #include "clang/Basic/LangOptions.h"
  24. #include "clang/Lex/HeaderSearch.h"
  25. #include "clang/Lex/ModuleLoader.h"
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "clang/Sema/DeclSpec.h"
  28. #include "clang/Sema/Lookup.h"
  29. #include "clang/Sema/Overload.h"
  30. #include "clang/Sema/Scope.h"
  31. #include "clang/Sema/ScopeInfo.h"
  32. #include "clang/Sema/Sema.h"
  33. #include "clang/Sema/SemaInternal.h"
  34. #include "clang/Sema/TemplateDeduction.h"
  35. #include "clang/Sema/TypoCorrection.h"
  36. #include "llvm/ADT/STLExtras.h"
  37. #include "llvm/ADT/SmallPtrSet.h"
  38. #include "llvm/ADT/TinyPtrVector.h"
  39. #include "llvm/ADT/edit_distance.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include <algorithm>
  42. #include <iterator>
  43. #include <list>
  44. #include <set>
  45. #include <utility>
  46. #include <vector>
  47. using namespace clang;
  48. using namespace sema;
  49. namespace {
  50. class UnqualUsingEntry {
  51. const DeclContext *Nominated;
  52. const DeclContext *CommonAncestor;
  53. public:
  54. UnqualUsingEntry(const DeclContext *Nominated,
  55. const DeclContext *CommonAncestor)
  56. : Nominated(Nominated), CommonAncestor(CommonAncestor) {
  57. }
  58. const DeclContext *getCommonAncestor() const {
  59. return CommonAncestor;
  60. }
  61. const DeclContext *getNominatedNamespace() const {
  62. return Nominated;
  63. }
  64. // Sort by the pointer value of the common ancestor.
  65. struct Comparator {
  66. bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
  67. return L.getCommonAncestor() < R.getCommonAncestor();
  68. }
  69. bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
  70. return E.getCommonAncestor() < DC;
  71. }
  72. bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
  73. return DC < E.getCommonAncestor();
  74. }
  75. };
  76. };
  77. /// A collection of using directives, as used by C++ unqualified
  78. /// lookup.
  79. class UnqualUsingDirectiveSet {
  80. Sema &SemaRef;
  81. typedef SmallVector<UnqualUsingEntry, 8> ListTy;
  82. ListTy list;
  83. llvm::SmallPtrSet<DeclContext*, 8> visited;
  84. public:
  85. UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
  86. void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
  87. // C++ [namespace.udir]p1:
  88. // During unqualified name lookup, the names appear as if they
  89. // were declared in the nearest enclosing namespace which contains
  90. // both the using-directive and the nominated namespace.
  91. DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
  92. assert(InnermostFileDC && InnermostFileDC->isFileContext());
  93. for (; S; S = S->getParent()) {
  94. // C++ [namespace.udir]p1:
  95. // A using-directive shall not appear in class scope, but may
  96. // appear in namespace scope or in block scope.
  97. DeclContext *Ctx = S->getEntity();
  98. if (Ctx && Ctx->isFileContext()) {
  99. visit(Ctx, Ctx);
  100. } else if (!Ctx || Ctx->isFunctionOrMethod()) {
  101. for (auto *I : S->using_directives())
  102. if (SemaRef.isVisible(I))
  103. visit(I, InnermostFileDC);
  104. }
  105. }
  106. }
  107. // Visits a context and collect all of its using directives
  108. // recursively. Treats all using directives as if they were
  109. // declared in the context.
  110. //
  111. // A given context is only every visited once, so it is important
  112. // that contexts be visited from the inside out in order to get
  113. // the effective DCs right.
  114. void visit(DeclContext *DC, DeclContext *EffectiveDC) {
  115. if (!visited.insert(DC).second)
  116. return;
  117. addUsingDirectives(DC, EffectiveDC);
  118. }
  119. // Visits a using directive and collects all of its using
  120. // directives recursively. Treats all using directives as if they
  121. // were declared in the effective DC.
  122. void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
  123. DeclContext *NS = UD->getNominatedNamespace();
  124. if (!visited.insert(NS).second)
  125. return;
  126. addUsingDirective(UD, EffectiveDC);
  127. addUsingDirectives(NS, EffectiveDC);
  128. }
  129. // Adds all the using directives in a context (and those nominated
  130. // by its using directives, transitively) as if they appeared in
  131. // the given effective context.
  132. void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
  133. SmallVector<DeclContext*, 4> queue;
  134. while (true) {
  135. for (auto UD : DC->using_directives()) {
  136. DeclContext *NS = UD->getNominatedNamespace();
  137. if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
  138. addUsingDirective(UD, EffectiveDC);
  139. queue.push_back(NS);
  140. }
  141. }
  142. if (queue.empty())
  143. return;
  144. DC = queue.pop_back_val();
  145. }
  146. }
  147. // Add a using directive as if it had been declared in the given
  148. // context. This helps implement C++ [namespace.udir]p3:
  149. // The using-directive is transitive: if a scope contains a
  150. // using-directive that nominates a second namespace that itself
  151. // contains using-directives, the effect is as if the
  152. // using-directives from the second namespace also appeared in
  153. // the first.
  154. void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
  155. // Find the common ancestor between the effective context and
  156. // the nominated namespace.
  157. DeclContext *Common = UD->getNominatedNamespace();
  158. while (!Common->Encloses(EffectiveDC))
  159. Common = Common->getParent();
  160. Common = Common->getPrimaryContext();
  161. list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
  162. }
  163. void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
  164. typedef ListTy::const_iterator const_iterator;
  165. const_iterator begin() const { return list.begin(); }
  166. const_iterator end() const { return list.end(); }
  167. llvm::iterator_range<const_iterator>
  168. getNamespacesFor(DeclContext *DC) const {
  169. return llvm::make_range(std::equal_range(begin(), end(),
  170. DC->getPrimaryContext(),
  171. UnqualUsingEntry::Comparator()));
  172. }
  173. };
  174. } // end anonymous namespace
  175. // Retrieve the set of identifier namespaces that correspond to a
  176. // specific kind of name lookup.
  177. static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
  178. bool CPlusPlus,
  179. bool Redeclaration) {
  180. unsigned IDNS = 0;
  181. switch (NameKind) {
  182. case Sema::LookupObjCImplicitSelfParam:
  183. case Sema::LookupOrdinaryName:
  184. case Sema::LookupRedeclarationWithLinkage:
  185. case Sema::LookupLocalFriendName:
  186. IDNS = Decl::IDNS_Ordinary;
  187. if (CPlusPlus) {
  188. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
  189. if (Redeclaration)
  190. IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
  191. }
  192. if (Redeclaration)
  193. IDNS |= Decl::IDNS_LocalExtern;
  194. break;
  195. case Sema::LookupOperatorName:
  196. // Operator lookup is its own crazy thing; it is not the same
  197. // as (e.g.) looking up an operator name for redeclaration.
  198. assert(!Redeclaration && "cannot do redeclaration operator lookup");
  199. IDNS = Decl::IDNS_NonMemberOperator;
  200. break;
  201. case Sema::LookupTagName:
  202. if (CPlusPlus) {
  203. IDNS = Decl::IDNS_Type;
  204. // When looking for a redeclaration of a tag name, we add:
  205. // 1) TagFriend to find undeclared friend decls
  206. // 2) Namespace because they can't "overload" with tag decls.
  207. // 3) Tag because it includes class templates, which can't
  208. // "overload" with tag decls.
  209. if (Redeclaration)
  210. IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
  211. } else {
  212. IDNS = Decl::IDNS_Tag;
  213. }
  214. break;
  215. case Sema::LookupLabel:
  216. IDNS = Decl::IDNS_Label;
  217. break;
  218. case Sema::LookupMemberName:
  219. IDNS = Decl::IDNS_Member;
  220. if (CPlusPlus)
  221. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
  222. break;
  223. case Sema::LookupNestedNameSpecifierName:
  224. IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
  225. break;
  226. case Sema::LookupNamespaceName:
  227. IDNS = Decl::IDNS_Namespace;
  228. break;
  229. case Sema::LookupUsingDeclName:
  230. assert(Redeclaration && "should only be used for redecl lookup");
  231. IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
  232. Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
  233. Decl::IDNS_LocalExtern;
  234. break;
  235. case Sema::LookupObjCProtocolName:
  236. IDNS = Decl::IDNS_ObjCProtocol;
  237. break;
  238. case Sema::LookupOMPReductionName:
  239. IDNS = Decl::IDNS_OMPReduction;
  240. break;
  241. case Sema::LookupOMPMapperName:
  242. IDNS = Decl::IDNS_OMPMapper;
  243. break;
  244. case Sema::LookupAnyName:
  245. IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
  246. | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
  247. | Decl::IDNS_Type;
  248. break;
  249. }
  250. return IDNS;
  251. }
  252. void LookupResult::configure() {
  253. IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
  254. isForRedeclaration());
  255. // If we're looking for one of the allocation or deallocation
  256. // operators, make sure that the implicitly-declared new and delete
  257. // operators can be found.
  258. switch (NameInfo.getName().getCXXOverloadedOperator()) {
  259. case OO_New:
  260. case OO_Delete:
  261. case OO_Array_New:
  262. case OO_Array_Delete:
  263. getSema().DeclareGlobalNewDelete();
  264. break;
  265. default:
  266. break;
  267. }
  268. // Compiler builtins are always visible, regardless of where they end
  269. // up being declared.
  270. if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
  271. if (unsigned BuiltinID = Id->getBuiltinID()) {
  272. if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  273. AllowHidden = true;
  274. }
  275. }
  276. }
  277. bool LookupResult::sanity() const {
  278. // This function is never called by NDEBUG builds.
  279. assert(ResultKind != NotFound || Decls.size() == 0);
  280. assert(ResultKind != Found || Decls.size() == 1);
  281. assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
  282. (Decls.size() == 1 &&
  283. isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
  284. assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
  285. assert(ResultKind != Ambiguous || Decls.size() > 1 ||
  286. (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
  287. Ambiguity == AmbiguousBaseSubobjectTypes)));
  288. assert((Paths != nullptr) == (ResultKind == Ambiguous &&
  289. (Ambiguity == AmbiguousBaseSubobjectTypes ||
  290. Ambiguity == AmbiguousBaseSubobjects)));
  291. return true;
  292. }
  293. // Necessary because CXXBasePaths is not complete in Sema.h
  294. void LookupResult::deletePaths(CXXBasePaths *Paths) {
  295. delete Paths;
  296. }
  297. /// Get a representative context for a declaration such that two declarations
  298. /// will have the same context if they were found within the same scope.
  299. static DeclContext *getContextForScopeMatching(Decl *D) {
  300. // For function-local declarations, use that function as the context. This
  301. // doesn't account for scopes within the function; the caller must deal with
  302. // those.
  303. DeclContext *DC = D->getLexicalDeclContext();
  304. if (DC->isFunctionOrMethod())
  305. return DC;
  306. // Otherwise, look at the semantic context of the declaration. The
  307. // declaration must have been found there.
  308. return D->getDeclContext()->getRedeclContext();
  309. }
  310. /// Determine whether \p D is a better lookup result than \p Existing,
  311. /// given that they declare the same entity.
  312. static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
  313. NamedDecl *D, NamedDecl *Existing) {
  314. // When looking up redeclarations of a using declaration, prefer a using
  315. // shadow declaration over any other declaration of the same entity.
  316. if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
  317. !isa<UsingShadowDecl>(Existing))
  318. return true;
  319. auto *DUnderlying = D->getUnderlyingDecl();
  320. auto *EUnderlying = Existing->getUnderlyingDecl();
  321. // If they have different underlying declarations, prefer a typedef over the
  322. // original type (this happens when two type declarations denote the same
  323. // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
  324. // might carry additional semantic information, such as an alignment override.
  325. // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
  326. // declaration over a typedef.
  327. if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
  328. assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
  329. bool HaveTag = isa<TagDecl>(EUnderlying);
  330. bool WantTag = Kind == Sema::LookupTagName;
  331. return HaveTag != WantTag;
  332. }
  333. // Pick the function with more default arguments.
  334. // FIXME: In the presence of ambiguous default arguments, we should keep both,
  335. // so we can diagnose the ambiguity if the default argument is needed.
  336. // See C++ [over.match.best]p3.
  337. if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
  338. auto *EFD = cast<FunctionDecl>(EUnderlying);
  339. unsigned DMin = DFD->getMinRequiredArguments();
  340. unsigned EMin = EFD->getMinRequiredArguments();
  341. // If D has more default arguments, it is preferred.
  342. if (DMin != EMin)
  343. return DMin < EMin;
  344. // FIXME: When we track visibility for default function arguments, check
  345. // that we pick the declaration with more visible default arguments.
  346. }
  347. // Pick the template with more default template arguments.
  348. if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
  349. auto *ETD = cast<TemplateDecl>(EUnderlying);
  350. unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
  351. unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
  352. // If D has more default arguments, it is preferred. Note that default
  353. // arguments (and their visibility) is monotonically increasing across the
  354. // redeclaration chain, so this is a quick proxy for "is more recent".
  355. if (DMin != EMin)
  356. return DMin < EMin;
  357. // If D has more *visible* default arguments, it is preferred. Note, an
  358. // earlier default argument being visible does not imply that a later
  359. // default argument is visible, so we can't just check the first one.
  360. for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
  361. I != N; ++I) {
  362. if (!S.hasVisibleDefaultArgument(
  363. ETD->getTemplateParameters()->getParam(I)) &&
  364. S.hasVisibleDefaultArgument(
  365. DTD->getTemplateParameters()->getParam(I)))
  366. return true;
  367. }
  368. }
  369. // VarDecl can have incomplete array types, prefer the one with more complete
  370. // array type.
  371. if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
  372. VarDecl *EVD = cast<VarDecl>(EUnderlying);
  373. if (EVD->getType()->isIncompleteType() &&
  374. !DVD->getType()->isIncompleteType()) {
  375. // Prefer the decl with a more complete type if visible.
  376. return S.isVisible(DVD);
  377. }
  378. return false; // Avoid picking up a newer decl, just because it was newer.
  379. }
  380. // For most kinds of declaration, it doesn't really matter which one we pick.
  381. if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
  382. // If the existing declaration is hidden, prefer the new one. Otherwise,
  383. // keep what we've got.
  384. return !S.isVisible(Existing);
  385. }
  386. // Pick the newer declaration; it might have a more precise type.
  387. for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
  388. Prev = Prev->getPreviousDecl())
  389. if (Prev == EUnderlying)
  390. return true;
  391. return false;
  392. }
  393. /// Determine whether \p D can hide a tag declaration.
  394. static bool canHideTag(NamedDecl *D) {
  395. // C++ [basic.scope.declarative]p4:
  396. // Given a set of declarations in a single declarative region [...]
  397. // exactly one declaration shall declare a class name or enumeration name
  398. // that is not a typedef name and the other declarations shall all refer to
  399. // the same variable, non-static data member, or enumerator, or all refer
  400. // to functions and function templates; in this case the class name or
  401. // enumeration name is hidden.
  402. // C++ [basic.scope.hiding]p2:
  403. // A class name or enumeration name can be hidden by the name of a
  404. // variable, data member, function, or enumerator declared in the same
  405. // scope.
  406. // An UnresolvedUsingValueDecl always instantiates to one of these.
  407. D = D->getUnderlyingDecl();
  408. return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
  409. isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
  410. isa<UnresolvedUsingValueDecl>(D);
  411. }
  412. /// Resolves the result kind of this lookup.
  413. void LookupResult::resolveKind() {
  414. unsigned N = Decls.size();
  415. // Fast case: no possible ambiguity.
  416. if (N == 0) {
  417. assert(ResultKind == NotFound ||
  418. ResultKind == NotFoundInCurrentInstantiation);
  419. return;
  420. }
  421. // If there's a single decl, we need to examine it to decide what
  422. // kind of lookup this is.
  423. if (N == 1) {
  424. NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
  425. if (isa<FunctionTemplateDecl>(D))
  426. ResultKind = FoundOverloaded;
  427. else if (isa<UnresolvedUsingValueDecl>(D))
  428. ResultKind = FoundUnresolvedValue;
  429. return;
  430. }
  431. // Don't do any extra resolution if we've already resolved as ambiguous.
  432. if (ResultKind == Ambiguous) return;
  433. llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
  434. llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
  435. bool Ambiguous = false;
  436. bool HasTag = false, HasFunction = false;
  437. bool HasFunctionTemplate = false, HasUnresolved = false;
  438. NamedDecl *HasNonFunction = nullptr;
  439. llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
  440. unsigned UniqueTagIndex = 0;
  441. unsigned I = 0;
  442. while (I < N) {
  443. NamedDecl *D = Decls[I]->getUnderlyingDecl();
  444. D = cast<NamedDecl>(D->getCanonicalDecl());
  445. // Ignore an invalid declaration unless it's the only one left.
  446. if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
  447. Decls[I] = Decls[--N];
  448. continue;
  449. }
  450. llvm::Optional<unsigned> ExistingI;
  451. // Redeclarations of types via typedef can occur both within a scope
  452. // and, through using declarations and directives, across scopes. There is
  453. // no ambiguity if they all refer to the same type, so unique based on the
  454. // canonical type.
  455. if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
  456. QualType T = getSema().Context.getTypeDeclType(TD);
  457. auto UniqueResult = UniqueTypes.insert(
  458. std::make_pair(getSema().Context.getCanonicalType(T), I));
  459. if (!UniqueResult.second) {
  460. // The type is not unique.
  461. ExistingI = UniqueResult.first->second;
  462. }
  463. }
  464. // For non-type declarations, check for a prior lookup result naming this
  465. // canonical declaration.
  466. if (!ExistingI) {
  467. auto UniqueResult = Unique.insert(std::make_pair(D, I));
  468. if (!UniqueResult.second) {
  469. // We've seen this entity before.
  470. ExistingI = UniqueResult.first->second;
  471. }
  472. }
  473. if (ExistingI) {
  474. // This is not a unique lookup result. Pick one of the results and
  475. // discard the other.
  476. if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
  477. Decls[*ExistingI]))
  478. Decls[*ExistingI] = Decls[I];
  479. Decls[I] = Decls[--N];
  480. continue;
  481. }
  482. // Otherwise, do some decl type analysis and then continue.
  483. if (isa<UnresolvedUsingValueDecl>(D)) {
  484. HasUnresolved = true;
  485. } else if (isa<TagDecl>(D)) {
  486. if (HasTag)
  487. Ambiguous = true;
  488. UniqueTagIndex = I;
  489. HasTag = true;
  490. } else if (isa<FunctionTemplateDecl>(D)) {
  491. HasFunction = true;
  492. HasFunctionTemplate = true;
  493. } else if (isa<FunctionDecl>(D)) {
  494. HasFunction = true;
  495. } else {
  496. if (HasNonFunction) {
  497. // If we're about to create an ambiguity between two declarations that
  498. // are equivalent, but one is an internal linkage declaration from one
  499. // module and the other is an internal linkage declaration from another
  500. // module, just skip it.
  501. if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
  502. D)) {
  503. EquivalentNonFunctions.push_back(D);
  504. Decls[I] = Decls[--N];
  505. continue;
  506. }
  507. Ambiguous = true;
  508. }
  509. HasNonFunction = D;
  510. }
  511. I++;
  512. }
  513. // C++ [basic.scope.hiding]p2:
  514. // A class name or enumeration name can be hidden by the name of
  515. // an object, function, or enumerator declared in the same
  516. // scope. If a class or enumeration name and an object, function,
  517. // or enumerator are declared in the same scope (in any order)
  518. // with the same name, the class or enumeration name is hidden
  519. // wherever the object, function, or enumerator name is visible.
  520. // But it's still an error if there are distinct tag types found,
  521. // even if they're not visible. (ref?)
  522. if (N > 1 && HideTags && HasTag && !Ambiguous &&
  523. (HasFunction || HasNonFunction || HasUnresolved)) {
  524. NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
  525. if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
  526. getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
  527. getContextForScopeMatching(OtherDecl)) &&
  528. canHideTag(OtherDecl))
  529. Decls[UniqueTagIndex] = Decls[--N];
  530. else
  531. Ambiguous = true;
  532. }
  533. // FIXME: This diagnostic should really be delayed until we're done with
  534. // the lookup result, in case the ambiguity is resolved by the caller.
  535. if (!EquivalentNonFunctions.empty() && !Ambiguous)
  536. getSema().diagnoseEquivalentInternalLinkageDeclarations(
  537. getNameLoc(), HasNonFunction, EquivalentNonFunctions);
  538. Decls.set_size(N);
  539. if (HasNonFunction && (HasFunction || HasUnresolved))
  540. Ambiguous = true;
  541. if (Ambiguous)
  542. setAmbiguous(LookupResult::AmbiguousReference);
  543. else if (HasUnresolved)
  544. ResultKind = LookupResult::FoundUnresolvedValue;
  545. else if (N > 1 || HasFunctionTemplate)
  546. ResultKind = LookupResult::FoundOverloaded;
  547. else
  548. ResultKind = LookupResult::Found;
  549. }
  550. void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
  551. CXXBasePaths::const_paths_iterator I, E;
  552. for (I = P.begin(), E = P.end(); I != E; ++I)
  553. for (DeclContext::lookup_iterator DI = I->Decls.begin(),
  554. DE = I->Decls.end(); DI != DE; ++DI)
  555. addDecl(*DI);
  556. }
  557. void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
  558. Paths = new CXXBasePaths;
  559. Paths->swap(P);
  560. addDeclsFromBasePaths(*Paths);
  561. resolveKind();
  562. setAmbiguous(AmbiguousBaseSubobjects);
  563. }
  564. void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
  565. Paths = new CXXBasePaths;
  566. Paths->swap(P);
  567. addDeclsFromBasePaths(*Paths);
  568. resolveKind();
  569. setAmbiguous(AmbiguousBaseSubobjectTypes);
  570. }
  571. void LookupResult::print(raw_ostream &Out) {
  572. Out << Decls.size() << " result(s)";
  573. if (isAmbiguous()) Out << ", ambiguous";
  574. if (Paths) Out << ", base paths present";
  575. for (iterator I = begin(), E = end(); I != E; ++I) {
  576. Out << "\n";
  577. (*I)->print(Out, 2);
  578. }
  579. }
  580. LLVM_DUMP_METHOD void LookupResult::dump() {
  581. llvm::errs() << "lookup results for " << getLookupName().getAsString()
  582. << ":\n";
  583. for (NamedDecl *D : *this)
  584. D->dump();
  585. }
  586. /// Lookup a builtin function, when name lookup would otherwise
  587. /// fail.
  588. static bool LookupBuiltin(Sema &S, LookupResult &R) {
  589. Sema::LookupNameKind NameKind = R.getLookupKind();
  590. // If we didn't find a use of this identifier, and if the identifier
  591. // corresponds to a compiler builtin, create the decl object for the builtin
  592. // now, injecting it into translation unit scope, and return it.
  593. if (NameKind == Sema::LookupOrdinaryName ||
  594. NameKind == Sema::LookupRedeclarationWithLinkage) {
  595. IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
  596. if (II) {
  597. if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
  598. if (II == S.getASTContext().getMakeIntegerSeqName()) {
  599. R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
  600. return true;
  601. } else if (II == S.getASTContext().getTypePackElementName()) {
  602. R.addDecl(S.getASTContext().getTypePackElementDecl());
  603. return true;
  604. }
  605. }
  606. // If this is a builtin on this (or all) targets, create the decl.
  607. if (unsigned BuiltinID = II->getBuiltinID()) {
  608. // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
  609. // library functions like 'malloc'. Instead, we'll just error.
  610. if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
  611. S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  612. return false;
  613. if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
  614. BuiltinID, S.TUScope,
  615. R.isForRedeclaration(),
  616. R.getNameLoc())) {
  617. R.addDecl(D);
  618. return true;
  619. }
  620. }
  621. }
  622. }
  623. return false;
  624. }
  625. /// Determine whether we can declare a special member function within
  626. /// the class at this point.
  627. static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
  628. // We need to have a definition for the class.
  629. if (!Class->getDefinition() || Class->isDependentContext())
  630. return false;
  631. // We can't be in the middle of defining the class.
  632. return !Class->isBeingDefined();
  633. }
  634. void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
  635. if (!CanDeclareSpecialMemberFunction(Class))
  636. return;
  637. // If the default constructor has not yet been declared, do so now.
  638. if (Class->needsImplicitDefaultConstructor())
  639. DeclareImplicitDefaultConstructor(Class);
  640. // If the copy constructor has not yet been declared, do so now.
  641. if (Class->needsImplicitCopyConstructor())
  642. DeclareImplicitCopyConstructor(Class);
  643. // If the copy assignment operator has not yet been declared, do so now.
  644. if (Class->needsImplicitCopyAssignment())
  645. DeclareImplicitCopyAssignment(Class);
  646. if (getLangOpts().CPlusPlus11) {
  647. // If the move constructor has not yet been declared, do so now.
  648. if (Class->needsImplicitMoveConstructor())
  649. DeclareImplicitMoveConstructor(Class);
  650. // If the move assignment operator has not yet been declared, do so now.
  651. if (Class->needsImplicitMoveAssignment())
  652. DeclareImplicitMoveAssignment(Class);
  653. }
  654. // If the destructor has not yet been declared, do so now.
  655. if (Class->needsImplicitDestructor())
  656. DeclareImplicitDestructor(Class);
  657. }
  658. /// Determine whether this is the name of an implicitly-declared
  659. /// special member function.
  660. static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
  661. switch (Name.getNameKind()) {
  662. case DeclarationName::CXXConstructorName:
  663. case DeclarationName::CXXDestructorName:
  664. return true;
  665. case DeclarationName::CXXOperatorName:
  666. return Name.getCXXOverloadedOperator() == OO_Equal;
  667. default:
  668. break;
  669. }
  670. return false;
  671. }
  672. /// If there are any implicit member functions with the given name
  673. /// that need to be declared in the given declaration context, do so.
  674. static void DeclareImplicitMemberFunctionsWithName(Sema &S,
  675. DeclarationName Name,
  676. SourceLocation Loc,
  677. const DeclContext *DC) {
  678. if (!DC)
  679. return;
  680. switch (Name.getNameKind()) {
  681. case DeclarationName::CXXConstructorName:
  682. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  683. if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
  684. CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
  685. if (Record->needsImplicitDefaultConstructor())
  686. S.DeclareImplicitDefaultConstructor(Class);
  687. if (Record->needsImplicitCopyConstructor())
  688. S.DeclareImplicitCopyConstructor(Class);
  689. if (S.getLangOpts().CPlusPlus11 &&
  690. Record->needsImplicitMoveConstructor())
  691. S.DeclareImplicitMoveConstructor(Class);
  692. }
  693. break;
  694. case DeclarationName::CXXDestructorName:
  695. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  696. if (Record->getDefinition() && Record->needsImplicitDestructor() &&
  697. CanDeclareSpecialMemberFunction(Record))
  698. S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
  699. break;
  700. case DeclarationName::CXXOperatorName:
  701. if (Name.getCXXOverloadedOperator() != OO_Equal)
  702. break;
  703. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
  704. if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
  705. CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
  706. if (Record->needsImplicitCopyAssignment())
  707. S.DeclareImplicitCopyAssignment(Class);
  708. if (S.getLangOpts().CPlusPlus11 &&
  709. Record->needsImplicitMoveAssignment())
  710. S.DeclareImplicitMoveAssignment(Class);
  711. }
  712. }
  713. break;
  714. case DeclarationName::CXXDeductionGuideName:
  715. S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
  716. break;
  717. default:
  718. break;
  719. }
  720. }
  721. // Adds all qualifying matches for a name within a decl context to the
  722. // given lookup result. Returns true if any matches were found.
  723. static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
  724. bool Found = false;
  725. // Lazily declare C++ special member functions.
  726. if (S.getLangOpts().CPlusPlus)
  727. DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
  728. DC);
  729. // Perform lookup into this declaration context.
  730. DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
  731. for (NamedDecl *D : DR) {
  732. if ((D = R.getAcceptableDecl(D))) {
  733. R.addDecl(D);
  734. Found = true;
  735. }
  736. }
  737. if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
  738. return true;
  739. if (R.getLookupName().getNameKind()
  740. != DeclarationName::CXXConversionFunctionName ||
  741. R.getLookupName().getCXXNameType()->isDependentType() ||
  742. !isa<CXXRecordDecl>(DC))
  743. return Found;
  744. // C++ [temp.mem]p6:
  745. // A specialization of a conversion function template is not found by
  746. // name lookup. Instead, any conversion function templates visible in the
  747. // context of the use are considered. [...]
  748. const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  749. if (!Record->isCompleteDefinition())
  750. return Found;
  751. // For conversion operators, 'operator auto' should only match
  752. // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
  753. // as a candidate for template substitution.
  754. auto *ContainedDeducedType =
  755. R.getLookupName().getCXXNameType()->getContainedDeducedType();
  756. if (R.getLookupName().getNameKind() ==
  757. DeclarationName::CXXConversionFunctionName &&
  758. ContainedDeducedType && ContainedDeducedType->isUndeducedType())
  759. return Found;
  760. for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
  761. UEnd = Record->conversion_end(); U != UEnd; ++U) {
  762. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
  763. if (!ConvTemplate)
  764. continue;
  765. // When we're performing lookup for the purposes of redeclaration, just
  766. // add the conversion function template. When we deduce template
  767. // arguments for specializations, we'll end up unifying the return
  768. // type of the new declaration with the type of the function template.
  769. if (R.isForRedeclaration()) {
  770. R.addDecl(ConvTemplate);
  771. Found = true;
  772. continue;
  773. }
  774. // C++ [temp.mem]p6:
  775. // [...] For each such operator, if argument deduction succeeds
  776. // (14.9.2.3), the resulting specialization is used as if found by
  777. // name lookup.
  778. //
  779. // When referencing a conversion function for any purpose other than
  780. // a redeclaration (such that we'll be building an expression with the
  781. // result), perform template argument deduction and place the
  782. // specialization into the result set. We do this to avoid forcing all
  783. // callers to perform special deduction for conversion functions.
  784. TemplateDeductionInfo Info(R.getNameLoc());
  785. FunctionDecl *Specialization = nullptr;
  786. const FunctionProtoType *ConvProto
  787. = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
  788. assert(ConvProto && "Nonsensical conversion function template type");
  789. // Compute the type of the function that we would expect the conversion
  790. // function to have, if it were to match the name given.
  791. // FIXME: Calling convention!
  792. FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
  793. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
  794. EPI.ExceptionSpec = EST_None;
  795. QualType ExpectedType
  796. = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
  797. None, EPI);
  798. // Perform template argument deduction against the type that we would
  799. // expect the function to have.
  800. if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
  801. Specialization, Info)
  802. == Sema::TDK_Success) {
  803. R.addDecl(Specialization);
  804. Found = true;
  805. }
  806. }
  807. return Found;
  808. }
  809. // Performs C++ unqualified lookup into the given file context.
  810. static bool
  811. CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
  812. DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
  813. assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
  814. // Perform direct name lookup into the LookupCtx.
  815. bool Found = LookupDirect(S, R, NS);
  816. // Perform direct name lookup into the namespaces nominated by the
  817. // using directives whose common ancestor is this namespace.
  818. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
  819. if (LookupDirect(S, R, UUE.getNominatedNamespace()))
  820. Found = true;
  821. R.resolveKind();
  822. return Found;
  823. }
  824. static bool isNamespaceOrTranslationUnitScope(Scope *S) {
  825. if (DeclContext *Ctx = S->getEntity())
  826. return Ctx->isFileContext();
  827. return false;
  828. }
  829. // Find the next outer declaration context from this scope. This
  830. // routine actually returns the semantic outer context, which may
  831. // differ from the lexical context (encoded directly in the Scope
  832. // stack) when we are parsing a member of a class template. In this
  833. // case, the second element of the pair will be true, to indicate that
  834. // name lookup should continue searching in this semantic context when
  835. // it leaves the current template parameter scope.
  836. static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
  837. DeclContext *DC = S->getEntity();
  838. DeclContext *Lexical = nullptr;
  839. for (Scope *OuterS = S->getParent(); OuterS;
  840. OuterS = OuterS->getParent()) {
  841. if (OuterS->getEntity()) {
  842. Lexical = OuterS->getEntity();
  843. break;
  844. }
  845. }
  846. // C++ [temp.local]p8:
  847. // In the definition of a member of a class template that appears
  848. // outside of the namespace containing the class template
  849. // definition, the name of a template-parameter hides the name of
  850. // a member of this namespace.
  851. //
  852. // Example:
  853. //
  854. // namespace N {
  855. // class C { };
  856. //
  857. // template<class T> class B {
  858. // void f(T);
  859. // };
  860. // }
  861. //
  862. // template<class C> void N::B<C>::f(C) {
  863. // C b; // C is the template parameter, not N::C
  864. // }
  865. //
  866. // In this example, the lexical context we return is the
  867. // TranslationUnit, while the semantic context is the namespace N.
  868. if (!Lexical || !DC || !S->getParent() ||
  869. !S->getParent()->isTemplateParamScope())
  870. return std::make_pair(Lexical, false);
  871. // Find the outermost template parameter scope.
  872. // For the example, this is the scope for the template parameters of
  873. // template<class C>.
  874. Scope *OutermostTemplateScope = S->getParent();
  875. while (OutermostTemplateScope->getParent() &&
  876. OutermostTemplateScope->getParent()->isTemplateParamScope())
  877. OutermostTemplateScope = OutermostTemplateScope->getParent();
  878. // Find the namespace context in which the original scope occurs. In
  879. // the example, this is namespace N.
  880. DeclContext *Semantic = DC;
  881. while (!Semantic->isFileContext())
  882. Semantic = Semantic->getParent();
  883. // Find the declaration context just outside of the template
  884. // parameter scope. This is the context in which the template is
  885. // being lexically declaration (a namespace context). In the
  886. // example, this is the global scope.
  887. if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
  888. Lexical->Encloses(Semantic))
  889. return std::make_pair(Semantic, true);
  890. return std::make_pair(Lexical, false);
  891. }
  892. namespace {
  893. /// An RAII object to specify that we want to find block scope extern
  894. /// declarations.
  895. struct FindLocalExternScope {
  896. FindLocalExternScope(LookupResult &R)
  897. : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
  898. Decl::IDNS_LocalExtern) {
  899. R.setFindLocalExtern(R.getIdentifierNamespace() &
  900. (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
  901. }
  902. void restore() {
  903. R.setFindLocalExtern(OldFindLocalExtern);
  904. }
  905. ~FindLocalExternScope() {
  906. restore();
  907. }
  908. LookupResult &R;
  909. bool OldFindLocalExtern;
  910. };
  911. } // end anonymous namespace
  912. bool Sema::CppLookupName(LookupResult &R, Scope *S) {
  913. assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
  914. DeclarationName Name = R.getLookupName();
  915. Sema::LookupNameKind NameKind = R.getLookupKind();
  916. // If this is the name of an implicitly-declared special member function,
  917. // go through the scope stack to implicitly declare
  918. if (isImplicitlyDeclaredMemberFunctionName(Name)) {
  919. for (Scope *PreS = S; PreS; PreS = PreS->getParent())
  920. if (DeclContext *DC = PreS->getEntity())
  921. DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
  922. }
  923. // Implicitly declare member functions with the name we're looking for, if in
  924. // fact we are in a scope where it matters.
  925. Scope *Initial = S;
  926. IdentifierResolver::iterator
  927. I = IdResolver.begin(Name),
  928. IEnd = IdResolver.end();
  929. // First we lookup local scope.
  930. // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
  931. // ...During unqualified name lookup (3.4.1), the names appear as if
  932. // they were declared in the nearest enclosing namespace which contains
  933. // both the using-directive and the nominated namespace.
  934. // [Note: in this context, "contains" means "contains directly or
  935. // indirectly".
  936. //
  937. // For example:
  938. // namespace A { int i; }
  939. // void foo() {
  940. // int i;
  941. // {
  942. // using namespace A;
  943. // ++i; // finds local 'i', A::i appears at global scope
  944. // }
  945. // }
  946. //
  947. UnqualUsingDirectiveSet UDirs(*this);
  948. bool VisitedUsingDirectives = false;
  949. bool LeftStartingScope = false;
  950. DeclContext *OutsideOfTemplateParamDC = nullptr;
  951. // When performing a scope lookup, we want to find local extern decls.
  952. FindLocalExternScope FindLocals(R);
  953. for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
  954. DeclContext *Ctx = S->getEntity();
  955. bool SearchNamespaceScope = true;
  956. // Check whether the IdResolver has anything in this scope.
  957. for (; I != IEnd && S->isDeclScope(*I); ++I) {
  958. if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
  959. if (NameKind == LookupRedeclarationWithLinkage &&
  960. !(*I)->isTemplateParameter()) {
  961. // If it's a template parameter, we still find it, so we can diagnose
  962. // the invalid redeclaration.
  963. // Determine whether this (or a previous) declaration is
  964. // out-of-scope.
  965. if (!LeftStartingScope && !Initial->isDeclScope(*I))
  966. LeftStartingScope = true;
  967. // If we found something outside of our starting scope that
  968. // does not have linkage, skip it.
  969. if (LeftStartingScope && !((*I)->hasLinkage())) {
  970. R.setShadowed();
  971. continue;
  972. }
  973. } else {
  974. // We found something in this scope, we should not look at the
  975. // namespace scope
  976. SearchNamespaceScope = false;
  977. }
  978. R.addDecl(ND);
  979. }
  980. }
  981. if (!SearchNamespaceScope) {
  982. R.resolveKind();
  983. if (S->isClassScope())
  984. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
  985. R.setNamingClass(Record);
  986. return true;
  987. }
  988. if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
  989. // C++11 [class.friend]p11:
  990. // If a friend declaration appears in a local class and the name
  991. // specified is an unqualified name, a prior declaration is
  992. // looked up without considering scopes that are outside the
  993. // innermost enclosing non-class scope.
  994. return false;
  995. }
  996. if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
  997. S->getParent() && !S->getParent()->isTemplateParamScope()) {
  998. // We've just searched the last template parameter scope and
  999. // found nothing, so look into the contexts between the
  1000. // lexical and semantic declaration contexts returned by
  1001. // findOuterContext(). This implements the name lookup behavior
  1002. // of C++ [temp.local]p8.
  1003. Ctx = OutsideOfTemplateParamDC;
  1004. OutsideOfTemplateParamDC = nullptr;
  1005. }
  1006. if (Ctx) {
  1007. DeclContext *OuterCtx;
  1008. bool SearchAfterTemplateScope;
  1009. std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
  1010. if (SearchAfterTemplateScope)
  1011. OutsideOfTemplateParamDC = OuterCtx;
  1012. for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
  1013. // We do not directly look into transparent contexts, since
  1014. // those entities will be found in the nearest enclosing
  1015. // non-transparent context.
  1016. if (Ctx->isTransparentContext())
  1017. continue;
  1018. // We do not look directly into function or method contexts,
  1019. // since all of the local variables and parameters of the
  1020. // function/method are present within the Scope.
  1021. if (Ctx->isFunctionOrMethod()) {
  1022. // If we have an Objective-C instance method, look for ivars
  1023. // in the corresponding interface.
  1024. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
  1025. if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
  1026. if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
  1027. ObjCInterfaceDecl *ClassDeclared;
  1028. if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
  1029. Name.getAsIdentifierInfo(),
  1030. ClassDeclared)) {
  1031. if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
  1032. R.addDecl(ND);
  1033. R.resolveKind();
  1034. return true;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. continue;
  1040. }
  1041. // If this is a file context, we need to perform unqualified name
  1042. // lookup considering using directives.
  1043. if (Ctx->isFileContext()) {
  1044. // If we haven't handled using directives yet, do so now.
  1045. if (!VisitedUsingDirectives) {
  1046. // Add using directives from this context up to the top level.
  1047. for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
  1048. if (UCtx->isTransparentContext())
  1049. continue;
  1050. UDirs.visit(UCtx, UCtx);
  1051. }
  1052. // Find the innermost file scope, so we can add using directives
  1053. // from local scopes.
  1054. Scope *InnermostFileScope = S;
  1055. while (InnermostFileScope &&
  1056. !isNamespaceOrTranslationUnitScope(InnermostFileScope))
  1057. InnermostFileScope = InnermostFileScope->getParent();
  1058. UDirs.visitScopeChain(Initial, InnermostFileScope);
  1059. UDirs.done();
  1060. VisitedUsingDirectives = true;
  1061. }
  1062. if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
  1063. R.resolveKind();
  1064. return true;
  1065. }
  1066. continue;
  1067. }
  1068. // Perform qualified name lookup into this context.
  1069. // FIXME: In some cases, we know that every name that could be found by
  1070. // this qualified name lookup will also be on the identifier chain. For
  1071. // example, inside a class without any base classes, we never need to
  1072. // perform qualified lookup because all of the members are on top of the
  1073. // identifier chain.
  1074. if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
  1075. return true;
  1076. }
  1077. }
  1078. }
  1079. // Stop if we ran out of scopes.
  1080. // FIXME: This really, really shouldn't be happening.
  1081. if (!S) return false;
  1082. // If we are looking for members, no need to look into global/namespace scope.
  1083. if (NameKind == LookupMemberName)
  1084. return false;
  1085. // Collect UsingDirectiveDecls in all scopes, and recursively all
  1086. // nominated namespaces by those using-directives.
  1087. //
  1088. // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
  1089. // don't build it for each lookup!
  1090. if (!VisitedUsingDirectives) {
  1091. UDirs.visitScopeChain(Initial, S);
  1092. UDirs.done();
  1093. }
  1094. // If we're not performing redeclaration lookup, do not look for local
  1095. // extern declarations outside of a function scope.
  1096. if (!R.isForRedeclaration())
  1097. FindLocals.restore();
  1098. // Lookup namespace scope, and global scope.
  1099. // Unqualified name lookup in C++ requires looking into scopes
  1100. // that aren't strictly lexical, and therefore we walk through the
  1101. // context as well as walking through the scopes.
  1102. for (; S; S = S->getParent()) {
  1103. // Check whether the IdResolver has anything in this scope.
  1104. bool Found = false;
  1105. for (; I != IEnd && S->isDeclScope(*I); ++I) {
  1106. if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
  1107. // We found something. Look for anything else in our scope
  1108. // with this same name and in an acceptable identifier
  1109. // namespace, so that we can construct an overload set if we
  1110. // need to.
  1111. Found = true;
  1112. R.addDecl(ND);
  1113. }
  1114. }
  1115. if (Found && S->isTemplateParamScope()) {
  1116. R.resolveKind();
  1117. return true;
  1118. }
  1119. DeclContext *Ctx = S->getEntity();
  1120. if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
  1121. S->getParent() && !S->getParent()->isTemplateParamScope()) {
  1122. // We've just searched the last template parameter scope and
  1123. // found nothing, so look into the contexts between the
  1124. // lexical and semantic declaration contexts returned by
  1125. // findOuterContext(). This implements the name lookup behavior
  1126. // of C++ [temp.local]p8.
  1127. Ctx = OutsideOfTemplateParamDC;
  1128. OutsideOfTemplateParamDC = nullptr;
  1129. }
  1130. if (Ctx) {
  1131. DeclContext *OuterCtx;
  1132. bool SearchAfterTemplateScope;
  1133. std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
  1134. if (SearchAfterTemplateScope)
  1135. OutsideOfTemplateParamDC = OuterCtx;
  1136. for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
  1137. // We do not directly look into transparent contexts, since
  1138. // those entities will be found in the nearest enclosing
  1139. // non-transparent context.
  1140. if (Ctx->isTransparentContext())
  1141. continue;
  1142. // If we have a context, and it's not a context stashed in the
  1143. // template parameter scope for an out-of-line definition, also
  1144. // look into that context.
  1145. if (!(Found && S->isTemplateParamScope())) {
  1146. assert(Ctx->isFileContext() &&
  1147. "We should have been looking only at file context here already.");
  1148. // Look into context considering using-directives.
  1149. if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
  1150. Found = true;
  1151. }
  1152. if (Found) {
  1153. R.resolveKind();
  1154. return true;
  1155. }
  1156. if (R.isForRedeclaration() && !Ctx->isTransparentContext())
  1157. return false;
  1158. }
  1159. }
  1160. if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
  1161. return false;
  1162. }
  1163. return !R.empty();
  1164. }
  1165. void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
  1166. if (auto *M = getCurrentModule())
  1167. Context.mergeDefinitionIntoModule(ND, M);
  1168. else
  1169. // We're not building a module; just make the definition visible.
  1170. ND->setVisibleDespiteOwningModule();
  1171. // If ND is a template declaration, make the template parameters
  1172. // visible too. They're not (necessarily) within a mergeable DeclContext.
  1173. if (auto *TD = dyn_cast<TemplateDecl>(ND))
  1174. for (auto *Param : *TD->getTemplateParameters())
  1175. makeMergedDefinitionVisible(Param);
  1176. }
  1177. /// Find the module in which the given declaration was defined.
  1178. static Module *getDefiningModule(Sema &S, Decl *Entity) {
  1179. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
  1180. // If this function was instantiated from a template, the defining module is
  1181. // the module containing the pattern.
  1182. if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
  1183. Entity = Pattern;
  1184. } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
  1185. if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
  1186. Entity = Pattern;
  1187. } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
  1188. if (auto *Pattern = ED->getTemplateInstantiationPattern())
  1189. Entity = Pattern;
  1190. } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
  1191. if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
  1192. Entity = Pattern;
  1193. }
  1194. // Walk up to the containing context. That might also have been instantiated
  1195. // from a template.
  1196. DeclContext *Context = Entity->getLexicalDeclContext();
  1197. if (Context->isFileContext())
  1198. return S.getOwningModule(Entity);
  1199. return getDefiningModule(S, cast<Decl>(Context));
  1200. }
  1201. llvm::DenseSet<Module*> &Sema::getLookupModules() {
  1202. unsigned N = CodeSynthesisContexts.size();
  1203. for (unsigned I = CodeSynthesisContextLookupModules.size();
  1204. I != N; ++I) {
  1205. Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity);
  1206. if (M && !LookupModulesCache.insert(M).second)
  1207. M = nullptr;
  1208. CodeSynthesisContextLookupModules.push_back(M);
  1209. }
  1210. return LookupModulesCache;
  1211. }
  1212. /// Determine whether the module M is part of the current module from the
  1213. /// perspective of a module-private visibility check.
  1214. static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
  1215. // If M is the global module fragment of a module that we've not yet finished
  1216. // parsing, then it must be part of the current module.
  1217. return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
  1218. (M->Kind == Module::GlobalModuleFragment && !M->Parent);
  1219. }
  1220. bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
  1221. for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
  1222. if (isModuleVisible(Merged))
  1223. return true;
  1224. return false;
  1225. }
  1226. bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
  1227. for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
  1228. if (isInCurrentModule(Merged, getLangOpts()))
  1229. return true;
  1230. return false;
  1231. }
  1232. template<typename ParmDecl>
  1233. static bool
  1234. hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
  1235. llvm::SmallVectorImpl<Module *> *Modules) {
  1236. if (!D->hasDefaultArgument())
  1237. return false;
  1238. while (D) {
  1239. auto &DefaultArg = D->getDefaultArgStorage();
  1240. if (!DefaultArg.isInherited() && S.isVisible(D))
  1241. return true;
  1242. if (!DefaultArg.isInherited() && Modules) {
  1243. auto *NonConstD = const_cast<ParmDecl*>(D);
  1244. Modules->push_back(S.getOwningModule(NonConstD));
  1245. }
  1246. // If there was a previous default argument, maybe its parameter is visible.
  1247. D = DefaultArg.getInheritedFrom();
  1248. }
  1249. return false;
  1250. }
  1251. bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
  1252. llvm::SmallVectorImpl<Module *> *Modules) {
  1253. if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
  1254. return ::hasVisibleDefaultArgument(*this, P, Modules);
  1255. if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
  1256. return ::hasVisibleDefaultArgument(*this, P, Modules);
  1257. return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
  1258. Modules);
  1259. }
  1260. template<typename Filter>
  1261. static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
  1262. llvm::SmallVectorImpl<Module *> *Modules,
  1263. Filter F) {
  1264. bool HasFilteredRedecls = false;
  1265. for (auto *Redecl : D->redecls()) {
  1266. auto *R = cast<NamedDecl>(Redecl);
  1267. if (!F(R))
  1268. continue;
  1269. if (S.isVisible(R))
  1270. return true;
  1271. HasFilteredRedecls = true;
  1272. if (Modules)
  1273. Modules->push_back(R->getOwningModule());
  1274. }
  1275. // Only return false if there is at least one redecl that is not filtered out.
  1276. if (HasFilteredRedecls)
  1277. return false;
  1278. return true;
  1279. }
  1280. bool Sema::hasVisibleExplicitSpecialization(
  1281. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1282. return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
  1283. if (auto *RD = dyn_cast<CXXRecordDecl>(D))
  1284. return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
  1285. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1286. return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
  1287. if (auto *VD = dyn_cast<VarDecl>(D))
  1288. return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
  1289. llvm_unreachable("unknown explicit specialization kind");
  1290. });
  1291. }
  1292. bool Sema::hasVisibleMemberSpecialization(
  1293. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1294. assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
  1295. "not a member specialization");
  1296. return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
  1297. // If the specialization is declared at namespace scope, then it's a member
  1298. // specialization declaration. If it's lexically inside the class
  1299. // definition then it was instantiated.
  1300. //
  1301. // FIXME: This is a hack. There should be a better way to determine this.
  1302. // FIXME: What about MS-style explicit specializations declared within a
  1303. // class definition?
  1304. return D->getLexicalDeclContext()->isFileContext();
  1305. });
  1306. }
  1307. /// Determine whether a declaration is visible to name lookup.
  1308. ///
  1309. /// This routine determines whether the declaration D is visible in the current
  1310. /// lookup context, taking into account the current template instantiation
  1311. /// stack. During template instantiation, a declaration is visible if it is
  1312. /// visible from a module containing any entity on the template instantiation
  1313. /// path (by instantiating a template, you allow it to see the declarations that
  1314. /// your module can see, including those later on in your module).
  1315. bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
  1316. assert(D->isHidden() && "should not call this: not in slow case");
  1317. Module *DeclModule = SemaRef.getOwningModule(D);
  1318. assert(DeclModule && "hidden decl has no owning module");
  1319. // If the owning module is visible, the decl is visible.
  1320. if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
  1321. return true;
  1322. // Determine whether a decl context is a file context for the purpose of
  1323. // visibility. This looks through some (export and linkage spec) transparent
  1324. // contexts, but not others (enums).
  1325. auto IsEffectivelyFileContext = [](const DeclContext *DC) {
  1326. return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
  1327. isa<ExportDecl>(DC);
  1328. };
  1329. // If this declaration is not at namespace scope
  1330. // then it is visible if its lexical parent has a visible definition.
  1331. DeclContext *DC = D->getLexicalDeclContext();
  1332. if (DC && !IsEffectivelyFileContext(DC)) {
  1333. // For a parameter, check whether our current template declaration's
  1334. // lexical context is visible, not whether there's some other visible
  1335. // definition of it, because parameters aren't "within" the definition.
  1336. //
  1337. // In C++ we need to check for a visible definition due to ODR merging,
  1338. // and in C we must not because each declaration of a function gets its own
  1339. // set of declarations for tags in prototype scope.
  1340. bool VisibleWithinParent;
  1341. if (D->isTemplateParameter() || isa<ParmVarDecl>(D) ||
  1342. (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
  1343. VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
  1344. else if (D->isModulePrivate()) {
  1345. // A module-private declaration is only visible if an enclosing lexical
  1346. // parent was merged with another definition in the current module.
  1347. VisibleWithinParent = false;
  1348. do {
  1349. if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
  1350. VisibleWithinParent = true;
  1351. break;
  1352. }
  1353. DC = DC->getLexicalParent();
  1354. } while (!IsEffectivelyFileContext(DC));
  1355. } else {
  1356. VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
  1357. }
  1358. if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
  1359. // FIXME: Do something better in this case.
  1360. !SemaRef.getLangOpts().ModulesLocalVisibility) {
  1361. // Cache the fact that this declaration is implicitly visible because
  1362. // its parent has a visible definition.
  1363. D->setVisibleDespiteOwningModule();
  1364. }
  1365. return VisibleWithinParent;
  1366. }
  1367. return false;
  1368. }
  1369. bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
  1370. // The module might be ordinarily visible. For a module-private query, that
  1371. // means it is part of the current module. For any other query, that means it
  1372. // is in our visible module set.
  1373. if (ModulePrivate) {
  1374. if (isInCurrentModule(M, getLangOpts()))
  1375. return true;
  1376. } else {
  1377. if (VisibleModules.isVisible(M))
  1378. return true;
  1379. }
  1380. // Otherwise, it might be visible by virtue of the query being within a
  1381. // template instantiation or similar that is permitted to look inside M.
  1382. // Find the extra places where we need to look.
  1383. const auto &LookupModules = getLookupModules();
  1384. if (LookupModules.empty())
  1385. return false;
  1386. // If our lookup set contains the module, it's visible.
  1387. if (LookupModules.count(M))
  1388. return true;
  1389. // For a module-private query, that's everywhere we get to look.
  1390. if (ModulePrivate)
  1391. return false;
  1392. // Check whether M is transitively exported to an import of the lookup set.
  1393. return llvm::any_of(LookupModules, [&](const Module *LookupM) {
  1394. return LookupM->isModuleVisible(M);
  1395. });
  1396. }
  1397. bool Sema::isVisibleSlow(const NamedDecl *D) {
  1398. return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
  1399. }
  1400. bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
  1401. // FIXME: If there are both visible and hidden declarations, we need to take
  1402. // into account whether redeclaration is possible. Example:
  1403. //
  1404. // Non-imported module:
  1405. // int f(T); // #1
  1406. // Some TU:
  1407. // static int f(U); // #2, not a redeclaration of #1
  1408. // int f(T); // #3, finds both, should link with #1 if T != U, but
  1409. // // with #2 if T == U; neither should be ambiguous.
  1410. for (auto *D : R) {
  1411. if (isVisible(D))
  1412. return true;
  1413. assert(D->isExternallyDeclarable() &&
  1414. "should not have hidden, non-externally-declarable result here");
  1415. }
  1416. // This function is called once "New" is essentially complete, but before a
  1417. // previous declaration is attached. We can't query the linkage of "New" in
  1418. // general, because attaching the previous declaration can change the
  1419. // linkage of New to match the previous declaration.
  1420. //
  1421. // However, because we've just determined that there is no *visible* prior
  1422. // declaration, we can compute the linkage here. There are two possibilities:
  1423. //
  1424. // * This is not a redeclaration; it's safe to compute the linkage now.
  1425. //
  1426. // * This is a redeclaration of a prior declaration that is externally
  1427. // redeclarable. In that case, the linkage of the declaration is not
  1428. // changed by attaching the prior declaration, because both are externally
  1429. // declarable (and thus ExternalLinkage or VisibleNoLinkage).
  1430. //
  1431. // FIXME: This is subtle and fragile.
  1432. return New->isExternallyDeclarable();
  1433. }
  1434. /// Retrieve the visible declaration corresponding to D, if any.
  1435. ///
  1436. /// This routine determines whether the declaration D is visible in the current
  1437. /// module, with the current imports. If not, it checks whether any
  1438. /// redeclaration of D is visible, and if so, returns that declaration.
  1439. ///
  1440. /// \returns D, or a visible previous declaration of D, whichever is more recent
  1441. /// and visible. If no declaration of D is visible, returns null.
  1442. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
  1443. unsigned IDNS) {
  1444. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  1445. for (auto RD : D->redecls()) {
  1446. // Don't bother with extra checks if we already know this one isn't visible.
  1447. if (RD == D)
  1448. continue;
  1449. auto ND = cast<NamedDecl>(RD);
  1450. // FIXME: This is wrong in the case where the previous declaration is not
  1451. // visible in the same scope as D. This needs to be done much more
  1452. // carefully.
  1453. if (ND->isInIdentifierNamespace(IDNS) &&
  1454. LookupResult::isVisible(SemaRef, ND))
  1455. return ND;
  1456. }
  1457. return nullptr;
  1458. }
  1459. bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
  1460. llvm::SmallVectorImpl<Module *> *Modules) {
  1461. assert(!isVisible(D) && "not in slow case");
  1462. return hasVisibleDeclarationImpl(*this, D, Modules,
  1463. [](const NamedDecl *) { return true; });
  1464. }
  1465. NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
  1466. if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
  1467. // Namespaces are a bit of a special case: we expect there to be a lot of
  1468. // redeclarations of some namespaces, all declarations of a namespace are
  1469. // essentially interchangeable, all declarations are found by name lookup
  1470. // if any is, and namespaces are never looked up during template
  1471. // instantiation. So we benefit from caching the check in this case, and
  1472. // it is correct to do so.
  1473. auto *Key = ND->getCanonicalDecl();
  1474. if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
  1475. return Acceptable;
  1476. auto *Acceptable = isVisible(getSema(), Key)
  1477. ? Key
  1478. : findAcceptableDecl(getSema(), Key, IDNS);
  1479. if (Acceptable)
  1480. getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
  1481. return Acceptable;
  1482. }
  1483. return findAcceptableDecl(getSema(), D, IDNS);
  1484. }
  1485. /// Perform unqualified name lookup starting from a given
  1486. /// scope.
  1487. ///
  1488. /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
  1489. /// used to find names within the current scope. For example, 'x' in
  1490. /// @code
  1491. /// int x;
  1492. /// int f() {
  1493. /// return x; // unqualified name look finds 'x' in the global scope
  1494. /// }
  1495. /// @endcode
  1496. ///
  1497. /// Different lookup criteria can find different names. For example, a
  1498. /// particular scope can have both a struct and a function of the same
  1499. /// name, and each can be found by certain lookup criteria. For more
  1500. /// information about lookup criteria, see the documentation for the
  1501. /// class LookupCriteria.
  1502. ///
  1503. /// @param S The scope from which unqualified name lookup will
  1504. /// begin. If the lookup criteria permits, name lookup may also search
  1505. /// in the parent scopes.
  1506. ///
  1507. /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
  1508. /// look up and the lookup kind), and is updated with the results of lookup
  1509. /// including zero or more declarations and possibly additional information
  1510. /// used to diagnose ambiguities.
  1511. ///
  1512. /// @returns \c true if lookup succeeded and false otherwise.
  1513. bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
  1514. DeclarationName Name = R.getLookupName();
  1515. if (!Name) return false;
  1516. LookupNameKind NameKind = R.getLookupKind();
  1517. if (!getLangOpts().CPlusPlus) {
  1518. // Unqualified name lookup in C/Objective-C is purely lexical, so
  1519. // search in the declarations attached to the name.
  1520. if (NameKind == Sema::LookupRedeclarationWithLinkage) {
  1521. // Find the nearest non-transparent declaration scope.
  1522. while (!(S->getFlags() & Scope::DeclScope) ||
  1523. (S->getEntity() && S->getEntity()->isTransparentContext()))
  1524. S = S->getParent();
  1525. }
  1526. // When performing a scope lookup, we want to find local extern decls.
  1527. FindLocalExternScope FindLocals(R);
  1528. // Scan up the scope chain looking for a decl that matches this
  1529. // identifier that is in the appropriate namespace. This search
  1530. // should not take long, as shadowing of names is uncommon, and
  1531. // deep shadowing is extremely uncommon.
  1532. bool LeftStartingScope = false;
  1533. for (IdentifierResolver::iterator I = IdResolver.begin(Name),
  1534. IEnd = IdResolver.end();
  1535. I != IEnd; ++I)
  1536. if (NamedDecl *D = R.getAcceptableDecl(*I)) {
  1537. if (NameKind == LookupRedeclarationWithLinkage) {
  1538. // Determine whether this (or a previous) declaration is
  1539. // out-of-scope.
  1540. if (!LeftStartingScope && !S->isDeclScope(*I))
  1541. LeftStartingScope = true;
  1542. // If we found something outside of our starting scope that
  1543. // does not have linkage, skip it.
  1544. if (LeftStartingScope && !((*I)->hasLinkage())) {
  1545. R.setShadowed();
  1546. continue;
  1547. }
  1548. }
  1549. else if (NameKind == LookupObjCImplicitSelfParam &&
  1550. !isa<ImplicitParamDecl>(*I))
  1551. continue;
  1552. R.addDecl(D);
  1553. // Check whether there are any other declarations with the same name
  1554. // and in the same scope.
  1555. if (I != IEnd) {
  1556. // Find the scope in which this declaration was declared (if it
  1557. // actually exists in a Scope).
  1558. while (S && !S->isDeclScope(D))
  1559. S = S->getParent();
  1560. // If the scope containing the declaration is the translation unit,
  1561. // then we'll need to perform our checks based on the matching
  1562. // DeclContexts rather than matching scopes.
  1563. if (S && isNamespaceOrTranslationUnitScope(S))
  1564. S = nullptr;
  1565. // Compute the DeclContext, if we need it.
  1566. DeclContext *DC = nullptr;
  1567. if (!S)
  1568. DC = (*I)->getDeclContext()->getRedeclContext();
  1569. IdentifierResolver::iterator LastI = I;
  1570. for (++LastI; LastI != IEnd; ++LastI) {
  1571. if (S) {
  1572. // Match based on scope.
  1573. if (!S->isDeclScope(*LastI))
  1574. break;
  1575. } else {
  1576. // Match based on DeclContext.
  1577. DeclContext *LastDC
  1578. = (*LastI)->getDeclContext()->getRedeclContext();
  1579. if (!LastDC->Equals(DC))
  1580. break;
  1581. }
  1582. // If the declaration is in the right namespace and visible, add it.
  1583. if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
  1584. R.addDecl(LastD);
  1585. }
  1586. R.resolveKind();
  1587. }
  1588. return true;
  1589. }
  1590. } else {
  1591. // Perform C++ unqualified name lookup.
  1592. if (CppLookupName(R, S))
  1593. return true;
  1594. }
  1595. // If we didn't find a use of this identifier, and if the identifier
  1596. // corresponds to a compiler builtin, create the decl object for the builtin
  1597. // now, injecting it into translation unit scope, and return it.
  1598. if (AllowBuiltinCreation && LookupBuiltin(*this, R))
  1599. return true;
  1600. // If we didn't find a use of this identifier, the ExternalSource
  1601. // may be able to handle the situation.
  1602. // Note: some lookup failures are expected!
  1603. // See e.g. R.isForRedeclaration().
  1604. return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
  1605. }
  1606. /// Perform qualified name lookup in the namespaces nominated by
  1607. /// using directives by the given context.
  1608. ///
  1609. /// C++98 [namespace.qual]p2:
  1610. /// Given X::m (where X is a user-declared namespace), or given \::m
  1611. /// (where X is the global namespace), let S be the set of all
  1612. /// declarations of m in X and in the transitive closure of all
  1613. /// namespaces nominated by using-directives in X and its used
  1614. /// namespaces, except that using-directives are ignored in any
  1615. /// namespace, including X, directly containing one or more
  1616. /// declarations of m. No namespace is searched more than once in
  1617. /// the lookup of a name. If S is the empty set, the program is
  1618. /// ill-formed. Otherwise, if S has exactly one member, or if the
  1619. /// context of the reference is a using-declaration
  1620. /// (namespace.udecl), S is the required set of declarations of
  1621. /// m. Otherwise if the use of m is not one that allows a unique
  1622. /// declaration to be chosen from S, the program is ill-formed.
  1623. ///
  1624. /// C++98 [namespace.qual]p5:
  1625. /// During the lookup of a qualified namespace member name, if the
  1626. /// lookup finds more than one declaration of the member, and if one
  1627. /// declaration introduces a class name or enumeration name and the
  1628. /// other declarations either introduce the same object, the same
  1629. /// enumerator or a set of functions, the non-type name hides the
  1630. /// class or enumeration name if and only if the declarations are
  1631. /// from the same namespace; otherwise (the declarations are from
  1632. /// different namespaces), the program is ill-formed.
  1633. static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
  1634. DeclContext *StartDC) {
  1635. assert(StartDC->isFileContext() && "start context is not a file context");
  1636. // We have not yet looked into these namespaces, much less added
  1637. // their "using-children" to the queue.
  1638. SmallVector<NamespaceDecl*, 8> Queue;
  1639. // We have at least added all these contexts to the queue.
  1640. llvm::SmallPtrSet<DeclContext*, 8> Visited;
  1641. Visited.insert(StartDC);
  1642. // We have already looked into the initial namespace; seed the queue
  1643. // with its using-children.
  1644. for (auto *I : StartDC->using_directives()) {
  1645. NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
  1646. if (S.isVisible(I) && Visited.insert(ND).second)
  1647. Queue.push_back(ND);
  1648. }
  1649. // The easiest way to implement the restriction in [namespace.qual]p5
  1650. // is to check whether any of the individual results found a tag
  1651. // and, if so, to declare an ambiguity if the final result is not
  1652. // a tag.
  1653. bool FoundTag = false;
  1654. bool FoundNonTag = false;
  1655. LookupResult LocalR(LookupResult::Temporary, R);
  1656. bool Found = false;
  1657. while (!Queue.empty()) {
  1658. NamespaceDecl *ND = Queue.pop_back_val();
  1659. // We go through some convolutions here to avoid copying results
  1660. // between LookupResults.
  1661. bool UseLocal = !R.empty();
  1662. LookupResult &DirectR = UseLocal ? LocalR : R;
  1663. bool FoundDirect = LookupDirect(S, DirectR, ND);
  1664. if (FoundDirect) {
  1665. // First do any local hiding.
  1666. DirectR.resolveKind();
  1667. // If the local result is a tag, remember that.
  1668. if (DirectR.isSingleTagDecl())
  1669. FoundTag = true;
  1670. else
  1671. FoundNonTag = true;
  1672. // Append the local results to the total results if necessary.
  1673. if (UseLocal) {
  1674. R.addAllDecls(LocalR);
  1675. LocalR.clear();
  1676. }
  1677. }
  1678. // If we find names in this namespace, ignore its using directives.
  1679. if (FoundDirect) {
  1680. Found = true;
  1681. continue;
  1682. }
  1683. for (auto I : ND->using_directives()) {
  1684. NamespaceDecl *Nom = I->getNominatedNamespace();
  1685. if (S.isVisible(I) && Visited.insert(Nom).second)
  1686. Queue.push_back(Nom);
  1687. }
  1688. }
  1689. if (Found) {
  1690. if (FoundTag && FoundNonTag)
  1691. R.setAmbiguousQualifiedTagHiding();
  1692. else
  1693. R.resolveKind();
  1694. }
  1695. return Found;
  1696. }
  1697. /// Callback that looks for any member of a class with the given name.
  1698. static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
  1699. CXXBasePath &Path, DeclarationName Name) {
  1700. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  1701. Path.Decls = BaseRecord->lookup(Name);
  1702. return !Path.Decls.empty();
  1703. }
  1704. /// Determine whether the given set of member declarations contains only
  1705. /// static members, nested types, and enumerators.
  1706. template<typename InputIterator>
  1707. static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
  1708. Decl *D = (*First)->getUnderlyingDecl();
  1709. if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
  1710. return true;
  1711. if (isa<CXXMethodDecl>(D)) {
  1712. // Determine whether all of the methods are static.
  1713. bool AllMethodsAreStatic = true;
  1714. for(; First != Last; ++First) {
  1715. D = (*First)->getUnderlyingDecl();
  1716. if (!isa<CXXMethodDecl>(D)) {
  1717. assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
  1718. break;
  1719. }
  1720. if (!cast<CXXMethodDecl>(D)->isStatic()) {
  1721. AllMethodsAreStatic = false;
  1722. break;
  1723. }
  1724. }
  1725. if (AllMethodsAreStatic)
  1726. return true;
  1727. }
  1728. return false;
  1729. }
  1730. /// Perform qualified name lookup into a given context.
  1731. ///
  1732. /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
  1733. /// names when the context of those names is explicit specified, e.g.,
  1734. /// "std::vector" or "x->member", or as part of unqualified name lookup.
  1735. ///
  1736. /// Different lookup criteria can find different names. For example, a
  1737. /// particular scope can have both a struct and a function of the same
  1738. /// name, and each can be found by certain lookup criteria. For more
  1739. /// information about lookup criteria, see the documentation for the
  1740. /// class LookupCriteria.
  1741. ///
  1742. /// \param R captures both the lookup criteria and any lookup results found.
  1743. ///
  1744. /// \param LookupCtx The context in which qualified name lookup will
  1745. /// search. If the lookup criteria permits, name lookup may also search
  1746. /// in the parent contexts or (for C++ classes) base classes.
  1747. ///
  1748. /// \param InUnqualifiedLookup true if this is qualified name lookup that
  1749. /// occurs as part of unqualified name lookup.
  1750. ///
  1751. /// \returns true if lookup succeeded, false if it failed.
  1752. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
  1753. bool InUnqualifiedLookup) {
  1754. assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
  1755. if (!R.getLookupName())
  1756. return false;
  1757. // Make sure that the declaration context is complete.
  1758. assert((!isa<TagDecl>(LookupCtx) ||
  1759. LookupCtx->isDependentContext() ||
  1760. cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
  1761. cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
  1762. "Declaration context must already be complete!");
  1763. struct QualifiedLookupInScope {
  1764. bool oldVal;
  1765. DeclContext *Context;
  1766. // Set flag in DeclContext informing debugger that we're looking for qualified name
  1767. QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
  1768. oldVal = ctx->setUseQualifiedLookup();
  1769. }
  1770. ~QualifiedLookupInScope() {
  1771. Context->setUseQualifiedLookup(oldVal);
  1772. }
  1773. } QL(LookupCtx);
  1774. if (LookupDirect(*this, R, LookupCtx)) {
  1775. R.resolveKind();
  1776. if (isa<CXXRecordDecl>(LookupCtx))
  1777. R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
  1778. return true;
  1779. }
  1780. // Don't descend into implied contexts for redeclarations.
  1781. // C++98 [namespace.qual]p6:
  1782. // In a declaration for a namespace member in which the
  1783. // declarator-id is a qualified-id, given that the qualified-id
  1784. // for the namespace member has the form
  1785. // nested-name-specifier unqualified-id
  1786. // the unqualified-id shall name a member of the namespace
  1787. // designated by the nested-name-specifier.
  1788. // See also [class.mfct]p5 and [class.static.data]p2.
  1789. if (R.isForRedeclaration())
  1790. return false;
  1791. // If this is a namespace, look it up in the implied namespaces.
  1792. if (LookupCtx->isFileContext())
  1793. return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
  1794. // If this isn't a C++ class, we aren't allowed to look into base
  1795. // classes, we're done.
  1796. CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
  1797. if (!LookupRec || !LookupRec->getDefinition())
  1798. return false;
  1799. // If we're performing qualified name lookup into a dependent class,
  1800. // then we are actually looking into a current instantiation. If we have any
  1801. // dependent base classes, then we either have to delay lookup until
  1802. // template instantiation time (at which point all bases will be available)
  1803. // or we have to fail.
  1804. if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
  1805. LookupRec->hasAnyDependentBases()) {
  1806. R.setNotFoundInCurrentInstantiation();
  1807. return false;
  1808. }
  1809. // Perform lookup into our base classes.
  1810. CXXBasePaths Paths;
  1811. Paths.setOrigin(LookupRec);
  1812. // Look for this member in our base classes
  1813. bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
  1814. DeclarationName Name) = nullptr;
  1815. switch (R.getLookupKind()) {
  1816. case LookupObjCImplicitSelfParam:
  1817. case LookupOrdinaryName:
  1818. case LookupMemberName:
  1819. case LookupRedeclarationWithLinkage:
  1820. case LookupLocalFriendName:
  1821. BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
  1822. break;
  1823. case LookupTagName:
  1824. BaseCallback = &CXXRecordDecl::FindTagMember;
  1825. break;
  1826. case LookupAnyName:
  1827. BaseCallback = &LookupAnyMember;
  1828. break;
  1829. case LookupOMPReductionName:
  1830. BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
  1831. break;
  1832. case LookupOMPMapperName:
  1833. BaseCallback = &CXXRecordDecl::FindOMPMapperMember;
  1834. break;
  1835. case LookupUsingDeclName:
  1836. // This lookup is for redeclarations only.
  1837. case LookupOperatorName:
  1838. case LookupNamespaceName:
  1839. case LookupObjCProtocolName:
  1840. case LookupLabel:
  1841. // These lookups will never find a member in a C++ class (or base class).
  1842. return false;
  1843. case LookupNestedNameSpecifierName:
  1844. BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
  1845. break;
  1846. }
  1847. DeclarationName Name = R.getLookupName();
  1848. if (!LookupRec->lookupInBases(
  1849. [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  1850. return BaseCallback(Specifier, Path, Name);
  1851. },
  1852. Paths))
  1853. return false;
  1854. R.setNamingClass(LookupRec);
  1855. // C++ [class.member.lookup]p2:
  1856. // [...] If the resulting set of declarations are not all from
  1857. // sub-objects of the same type, or the set has a nonstatic member
  1858. // and includes members from distinct sub-objects, there is an
  1859. // ambiguity and the program is ill-formed. Otherwise that set is
  1860. // the result of the lookup.
  1861. QualType SubobjectType;
  1862. int SubobjectNumber = 0;
  1863. AccessSpecifier SubobjectAccess = AS_none;
  1864. for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
  1865. Path != PathEnd; ++Path) {
  1866. const CXXBasePathElement &PathElement = Path->back();
  1867. // Pick the best (i.e. most permissive i.e. numerically lowest) access
  1868. // across all paths.
  1869. SubobjectAccess = std::min(SubobjectAccess, Path->Access);
  1870. // Determine whether we're looking at a distinct sub-object or not.
  1871. if (SubobjectType.isNull()) {
  1872. // This is the first subobject we've looked at. Record its type.
  1873. SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
  1874. SubobjectNumber = PathElement.SubobjectNumber;
  1875. continue;
  1876. }
  1877. if (SubobjectType
  1878. != Context.getCanonicalType(PathElement.Base->getType())) {
  1879. // We found members of the given name in two subobjects of
  1880. // different types. If the declaration sets aren't the same, this
  1881. // lookup is ambiguous.
  1882. if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
  1883. CXXBasePaths::paths_iterator FirstPath = Paths.begin();
  1884. DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
  1885. DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
  1886. while (FirstD != FirstPath->Decls.end() &&
  1887. CurrentD != Path->Decls.end()) {
  1888. if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
  1889. (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
  1890. break;
  1891. ++FirstD;
  1892. ++CurrentD;
  1893. }
  1894. if (FirstD == FirstPath->Decls.end() &&
  1895. CurrentD == Path->Decls.end())
  1896. continue;
  1897. }
  1898. R.setAmbiguousBaseSubobjectTypes(Paths);
  1899. return true;
  1900. }
  1901. if (SubobjectNumber != PathElement.SubobjectNumber) {
  1902. // We have a different subobject of the same type.
  1903. // C++ [class.member.lookup]p5:
  1904. // A static member, a nested type or an enumerator defined in
  1905. // a base class T can unambiguously be found even if an object
  1906. // has more than one base class subobject of type T.
  1907. if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
  1908. continue;
  1909. // We have found a nonstatic member name in multiple, distinct
  1910. // subobjects. Name lookup is ambiguous.
  1911. R.setAmbiguousBaseSubobjects(Paths);
  1912. return true;
  1913. }
  1914. }
  1915. // Lookup in a base class succeeded; return these results.
  1916. for (auto *D : Paths.front().Decls) {
  1917. AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
  1918. D->getAccess());
  1919. R.addDecl(D, AS);
  1920. }
  1921. R.resolveKind();
  1922. return true;
  1923. }
  1924. /// Performs qualified name lookup or special type of lookup for
  1925. /// "__super::" scope specifier.
  1926. ///
  1927. /// This routine is a convenience overload meant to be called from contexts
  1928. /// that need to perform a qualified name lookup with an optional C++ scope
  1929. /// specifier that might require special kind of lookup.
  1930. ///
  1931. /// \param R captures both the lookup criteria and any lookup results found.
  1932. ///
  1933. /// \param LookupCtx The context in which qualified name lookup will
  1934. /// search.
  1935. ///
  1936. /// \param SS An optional C++ scope-specifier.
  1937. ///
  1938. /// \returns true if lookup succeeded, false if it failed.
  1939. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
  1940. CXXScopeSpec &SS) {
  1941. auto *NNS = SS.getScopeRep();
  1942. if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
  1943. return LookupInSuper(R, NNS->getAsRecordDecl());
  1944. else
  1945. return LookupQualifiedName(R, LookupCtx);
  1946. }
  1947. /// Performs name lookup for a name that was parsed in the
  1948. /// source code, and may contain a C++ scope specifier.
  1949. ///
  1950. /// This routine is a convenience routine meant to be called from
  1951. /// contexts that receive a name and an optional C++ scope specifier
  1952. /// (e.g., "N::M::x"). It will then perform either qualified or
  1953. /// unqualified name lookup (with LookupQualifiedName or LookupName,
  1954. /// respectively) on the given name and return those results. It will
  1955. /// perform a special type of lookup for "__super::" scope specifier.
  1956. ///
  1957. /// @param S The scope from which unqualified name lookup will
  1958. /// begin.
  1959. ///
  1960. /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
  1961. ///
  1962. /// @param EnteringContext Indicates whether we are going to enter the
  1963. /// context of the scope-specifier SS (if present).
  1964. ///
  1965. /// @returns True if any decls were found (but possibly ambiguous)
  1966. bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
  1967. bool AllowBuiltinCreation, bool EnteringContext) {
  1968. if (SS && SS->isInvalid()) {
  1969. // When the scope specifier is invalid, don't even look for
  1970. // anything.
  1971. return false;
  1972. }
  1973. if (SS && SS->isSet()) {
  1974. NestedNameSpecifier *NNS = SS->getScopeRep();
  1975. if (NNS->getKind() == NestedNameSpecifier::Super)
  1976. return LookupInSuper(R, NNS->getAsRecordDecl());
  1977. if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
  1978. // We have resolved the scope specifier to a particular declaration
  1979. // contex, and will perform name lookup in that context.
  1980. if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
  1981. return false;
  1982. R.setContextRange(SS->getRange());
  1983. return LookupQualifiedName(R, DC);
  1984. }
  1985. // We could not resolve the scope specified to a specific declaration
  1986. // context, which means that SS refers to an unknown specialization.
  1987. // Name lookup can't find anything in this case.
  1988. R.setNotFoundInCurrentInstantiation();
  1989. R.setContextRange(SS->getRange());
  1990. return false;
  1991. }
  1992. // Perform unqualified name lookup starting in the given scope.
  1993. return LookupName(R, S, AllowBuiltinCreation);
  1994. }
  1995. /// Perform qualified name lookup into all base classes of the given
  1996. /// class.
  1997. ///
  1998. /// \param R captures both the lookup criteria and any lookup results found.
  1999. ///
  2000. /// \param Class The context in which qualified name lookup will
  2001. /// search. Name lookup will search in all base classes merging the results.
  2002. ///
  2003. /// @returns True if any decls were found (but possibly ambiguous)
  2004. bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
  2005. // The access-control rules we use here are essentially the rules for
  2006. // doing a lookup in Class that just magically skipped the direct
  2007. // members of Class itself. That is, the naming class is Class, and the
  2008. // access includes the access of the base.
  2009. for (const auto &BaseSpec : Class->bases()) {
  2010. CXXRecordDecl *RD = cast<CXXRecordDecl>(
  2011. BaseSpec.getType()->castAs<RecordType>()->getDecl());
  2012. LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
  2013. Result.setBaseObjectType(Context.getRecordType(Class));
  2014. LookupQualifiedName(Result, RD);
  2015. // Copy the lookup results into the target, merging the base's access into
  2016. // the path access.
  2017. for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
  2018. R.addDecl(I.getDecl(),
  2019. CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
  2020. I.getAccess()));
  2021. }
  2022. Result.suppressDiagnostics();
  2023. }
  2024. R.resolveKind();
  2025. R.setNamingClass(Class);
  2026. return !R.empty();
  2027. }
  2028. /// Produce a diagnostic describing the ambiguity that resulted
  2029. /// from name lookup.
  2030. ///
  2031. /// \param Result The result of the ambiguous lookup to be diagnosed.
  2032. void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
  2033. assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
  2034. DeclarationName Name = Result.getLookupName();
  2035. SourceLocation NameLoc = Result.getNameLoc();
  2036. SourceRange LookupRange = Result.getContextRange();
  2037. switch (Result.getAmbiguityKind()) {
  2038. case LookupResult::AmbiguousBaseSubobjects: {
  2039. CXXBasePaths *Paths = Result.getBasePaths();
  2040. QualType SubobjectType = Paths->front().back().Base->getType();
  2041. Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
  2042. << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
  2043. << LookupRange;
  2044. DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
  2045. while (isa<CXXMethodDecl>(*Found) &&
  2046. cast<CXXMethodDecl>(*Found)->isStatic())
  2047. ++Found;
  2048. Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
  2049. break;
  2050. }
  2051. case LookupResult::AmbiguousBaseSubobjectTypes: {
  2052. Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
  2053. << Name << LookupRange;
  2054. CXXBasePaths *Paths = Result.getBasePaths();
  2055. std::set<Decl *> DeclsPrinted;
  2056. for (CXXBasePaths::paths_iterator Path = Paths->begin(),
  2057. PathEnd = Paths->end();
  2058. Path != PathEnd; ++Path) {
  2059. Decl *D = Path->Decls.front();
  2060. if (DeclsPrinted.insert(D).second)
  2061. Diag(D->getLocation(), diag::note_ambiguous_member_found);
  2062. }
  2063. break;
  2064. }
  2065. case LookupResult::AmbiguousTagHiding: {
  2066. Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
  2067. llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
  2068. for (auto *D : Result)
  2069. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  2070. TagDecls.insert(TD);
  2071. Diag(TD->getLocation(), diag::note_hidden_tag);
  2072. }
  2073. for (auto *D : Result)
  2074. if (!isa<TagDecl>(D))
  2075. Diag(D->getLocation(), diag::note_hiding_object);
  2076. // For recovery purposes, go ahead and implement the hiding.
  2077. LookupResult::Filter F = Result.makeFilter();
  2078. while (F.hasNext()) {
  2079. if (TagDecls.count(F.next()))
  2080. F.erase();
  2081. }
  2082. F.done();
  2083. break;
  2084. }
  2085. case LookupResult::AmbiguousReference: {
  2086. Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
  2087. for (auto *D : Result)
  2088. Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
  2089. break;
  2090. }
  2091. }
  2092. }
  2093. namespace {
  2094. struct AssociatedLookup {
  2095. AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
  2096. Sema::AssociatedNamespaceSet &Namespaces,
  2097. Sema::AssociatedClassSet &Classes)
  2098. : S(S), Namespaces(Namespaces), Classes(Classes),
  2099. InstantiationLoc(InstantiationLoc) {
  2100. }
  2101. bool addClassTransitive(CXXRecordDecl *RD) {
  2102. Classes.insert(RD);
  2103. return ClassesTransitive.insert(RD);
  2104. }
  2105. Sema &S;
  2106. Sema::AssociatedNamespaceSet &Namespaces;
  2107. Sema::AssociatedClassSet &Classes;
  2108. SourceLocation InstantiationLoc;
  2109. private:
  2110. Sema::AssociatedClassSet ClassesTransitive;
  2111. };
  2112. } // end anonymous namespace
  2113. static void
  2114. addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
  2115. static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
  2116. DeclContext *Ctx) {
  2117. // Add the associated namespace for this class.
  2118. // We don't use DeclContext::getEnclosingNamespaceContext() as this may
  2119. // be a locally scoped record.
  2120. // We skip out of inline namespaces. The innermost non-inline namespace
  2121. // contains all names of all its nested inline namespaces anyway, so we can
  2122. // replace the entire inline namespace tree with its root.
  2123. while (Ctx->isRecord() || Ctx->isTransparentContext() ||
  2124. Ctx->isInlineNamespace())
  2125. Ctx = Ctx->getParent();
  2126. if (Ctx->isFileContext())
  2127. Namespaces.insert(Ctx->getPrimaryContext());
  2128. }
  2129. // Add the associated classes and namespaces for argument-dependent
  2130. // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
  2131. static void
  2132. addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
  2133. const TemplateArgument &Arg) {
  2134. // C++ [basic.lookup.koenig]p2, last bullet:
  2135. // -- [...] ;
  2136. switch (Arg.getKind()) {
  2137. case TemplateArgument::Null:
  2138. break;
  2139. case TemplateArgument::Type:
  2140. // [...] the namespaces and classes associated with the types of the
  2141. // template arguments provided for template type parameters (excluding
  2142. // template template parameters)
  2143. addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
  2144. break;
  2145. case TemplateArgument::Template:
  2146. case TemplateArgument::TemplateExpansion: {
  2147. // [...] the namespaces in which any template template arguments are
  2148. // defined; and the classes in which any member templates used as
  2149. // template template arguments are defined.
  2150. TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
  2151. if (ClassTemplateDecl *ClassTemplate
  2152. = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
  2153. DeclContext *Ctx = ClassTemplate->getDeclContext();
  2154. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2155. Result.Classes.insert(EnclosingClass);
  2156. // Add the associated namespace for this class.
  2157. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2158. }
  2159. break;
  2160. }
  2161. case TemplateArgument::Declaration:
  2162. case TemplateArgument::Integral:
  2163. case TemplateArgument::Expression:
  2164. case TemplateArgument::NullPtr:
  2165. // [Note: non-type template arguments do not contribute to the set of
  2166. // associated namespaces. ]
  2167. break;
  2168. case TemplateArgument::Pack:
  2169. for (const auto &P : Arg.pack_elements())
  2170. addAssociatedClassesAndNamespaces(Result, P);
  2171. break;
  2172. }
  2173. }
  2174. // Add the associated classes and namespaces for
  2175. // argument-dependent lookup with an argument of class type
  2176. // (C++ [basic.lookup.koenig]p2).
  2177. static void
  2178. addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
  2179. CXXRecordDecl *Class) {
  2180. // Just silently ignore anything whose name is __va_list_tag.
  2181. if (Class->getDeclName() == Result.S.VAListTagName)
  2182. return;
  2183. // C++ [basic.lookup.koenig]p2:
  2184. // [...]
  2185. // -- If T is a class type (including unions), its associated
  2186. // classes are: the class itself; the class of which it is a
  2187. // member, if any; and its direct and indirect base
  2188. // classes. Its associated namespaces are the namespaces in
  2189. // which its associated classes are defined.
  2190. // Add the class of which it is a member, if any.
  2191. DeclContext *Ctx = Class->getDeclContext();
  2192. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2193. Result.Classes.insert(EnclosingClass);
  2194. // Add the associated namespace for this class.
  2195. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2196. // -- If T is a template-id, its associated namespaces and classes are
  2197. // the namespace in which the template is defined; for member
  2198. // templates, the member template's class; the namespaces and classes
  2199. // associated with the types of the template arguments provided for
  2200. // template type parameters (excluding template template parameters); the
  2201. // namespaces in which any template template arguments are defined; and
  2202. // the classes in which any member templates used as template template
  2203. // arguments are defined. [Note: non-type template arguments do not
  2204. // contribute to the set of associated namespaces. ]
  2205. if (ClassTemplateSpecializationDecl *Spec
  2206. = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
  2207. DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
  2208. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2209. Result.Classes.insert(EnclosingClass);
  2210. // Add the associated namespace for this class.
  2211. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2212. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  2213. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  2214. addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
  2215. }
  2216. // Add the class itself. If we've already transitively visited this class,
  2217. // we don't need to visit base classes.
  2218. if (!Result.addClassTransitive(Class))
  2219. return;
  2220. // Only recurse into base classes for complete types.
  2221. if (!Result.S.isCompleteType(Result.InstantiationLoc,
  2222. Result.S.Context.getRecordType(Class)))
  2223. return;
  2224. // Add direct and indirect base classes along with their associated
  2225. // namespaces.
  2226. SmallVector<CXXRecordDecl *, 32> Bases;
  2227. Bases.push_back(Class);
  2228. while (!Bases.empty()) {
  2229. // Pop this class off the stack.
  2230. Class = Bases.pop_back_val();
  2231. // Visit the base classes.
  2232. for (const auto &Base : Class->bases()) {
  2233. const RecordType *BaseType = Base.getType()->getAs<RecordType>();
  2234. // In dependent contexts, we do ADL twice, and the first time around,
  2235. // the base type might be a dependent TemplateSpecializationType, or a
  2236. // TemplateTypeParmType. If that happens, simply ignore it.
  2237. // FIXME: If we want to support export, we probably need to add the
  2238. // namespace of the template in a TemplateSpecializationType, or even
  2239. // the classes and namespaces of known non-dependent arguments.
  2240. if (!BaseType)
  2241. continue;
  2242. CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  2243. if (Result.addClassTransitive(BaseDecl)) {
  2244. // Find the associated namespace for this base class.
  2245. DeclContext *BaseCtx = BaseDecl->getDeclContext();
  2246. CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
  2247. // Make sure we visit the bases of this base class.
  2248. if (BaseDecl->bases_begin() != BaseDecl->bases_end())
  2249. Bases.push_back(BaseDecl);
  2250. }
  2251. }
  2252. }
  2253. }
  2254. // Add the associated classes and namespaces for
  2255. // argument-dependent lookup with an argument of type T
  2256. // (C++ [basic.lookup.koenig]p2).
  2257. static void
  2258. addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
  2259. // C++ [basic.lookup.koenig]p2:
  2260. //
  2261. // For each argument type T in the function call, there is a set
  2262. // of zero or more associated namespaces and a set of zero or more
  2263. // associated classes to be considered. The sets of namespaces and
  2264. // classes is determined entirely by the types of the function
  2265. // arguments (and the namespace of any template template
  2266. // argument). Typedef names and using-declarations used to specify
  2267. // the types do not contribute to this set. The sets of namespaces
  2268. // and classes are determined in the following way:
  2269. SmallVector<const Type *, 16> Queue;
  2270. const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
  2271. while (true) {
  2272. switch (T->getTypeClass()) {
  2273. #define TYPE(Class, Base)
  2274. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2275. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2276. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  2277. #define ABSTRACT_TYPE(Class, Base)
  2278. #include "clang/AST/TypeNodes.def"
  2279. // T is canonical. We can also ignore dependent types because
  2280. // we don't need to do ADL at the definition point, but if we
  2281. // wanted to implement template export (or if we find some other
  2282. // use for associated classes and namespaces...) this would be
  2283. // wrong.
  2284. break;
  2285. // -- If T is a pointer to U or an array of U, its associated
  2286. // namespaces and classes are those associated with U.
  2287. case Type::Pointer:
  2288. T = cast<PointerType>(T)->getPointeeType().getTypePtr();
  2289. continue;
  2290. case Type::ConstantArray:
  2291. case Type::IncompleteArray:
  2292. case Type::VariableArray:
  2293. T = cast<ArrayType>(T)->getElementType().getTypePtr();
  2294. continue;
  2295. // -- If T is a fundamental type, its associated sets of
  2296. // namespaces and classes are both empty.
  2297. case Type::Builtin:
  2298. break;
  2299. // -- If T is a class type (including unions), its associated
  2300. // classes are: the class itself; the class of which it is a
  2301. // member, if any; and its direct and indirect base
  2302. // classes. Its associated namespaces are the namespaces in
  2303. // which its associated classes are defined.
  2304. case Type::Record: {
  2305. CXXRecordDecl *Class =
  2306. cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
  2307. addAssociatedClassesAndNamespaces(Result, Class);
  2308. break;
  2309. }
  2310. // -- If T is an enumeration type, its associated namespace is
  2311. // the namespace in which it is defined. If it is class
  2312. // member, its associated class is the member's class; else
  2313. // it has no associated class.
  2314. case Type::Enum: {
  2315. EnumDecl *Enum = cast<EnumType>(T)->getDecl();
  2316. DeclContext *Ctx = Enum->getDeclContext();
  2317. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2318. Result.Classes.insert(EnclosingClass);
  2319. // Add the associated namespace for this class.
  2320. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2321. break;
  2322. }
  2323. // -- If T is a function type, its associated namespaces and
  2324. // classes are those associated with the function parameter
  2325. // types and those associated with the return type.
  2326. case Type::FunctionProto: {
  2327. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  2328. for (const auto &Arg : Proto->param_types())
  2329. Queue.push_back(Arg.getTypePtr());
  2330. // fallthrough
  2331. LLVM_FALLTHROUGH;
  2332. }
  2333. case Type::FunctionNoProto: {
  2334. const FunctionType *FnType = cast<FunctionType>(T);
  2335. T = FnType->getReturnType().getTypePtr();
  2336. continue;
  2337. }
  2338. // -- If T is a pointer to a member function of a class X, its
  2339. // associated namespaces and classes are those associated
  2340. // with the function parameter types and return type,
  2341. // together with those associated with X.
  2342. //
  2343. // -- If T is a pointer to a data member of class X, its
  2344. // associated namespaces and classes are those associated
  2345. // with the member type together with those associated with
  2346. // X.
  2347. case Type::MemberPointer: {
  2348. const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
  2349. // Queue up the class type into which this points.
  2350. Queue.push_back(MemberPtr->getClass());
  2351. // And directly continue with the pointee type.
  2352. T = MemberPtr->getPointeeType().getTypePtr();
  2353. continue;
  2354. }
  2355. // As an extension, treat this like a normal pointer.
  2356. case Type::BlockPointer:
  2357. T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
  2358. continue;
  2359. // References aren't covered by the standard, but that's such an
  2360. // obvious defect that we cover them anyway.
  2361. case Type::LValueReference:
  2362. case Type::RValueReference:
  2363. T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
  2364. continue;
  2365. // These are fundamental types.
  2366. case Type::Vector:
  2367. case Type::ExtVector:
  2368. case Type::Complex:
  2369. break;
  2370. // Non-deduced auto types only get here for error cases.
  2371. case Type::Auto:
  2372. case Type::DeducedTemplateSpecialization:
  2373. break;
  2374. // If T is an Objective-C object or interface type, or a pointer to an
  2375. // object or interface type, the associated namespace is the global
  2376. // namespace.
  2377. case Type::ObjCObject:
  2378. case Type::ObjCInterface:
  2379. case Type::ObjCObjectPointer:
  2380. Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
  2381. break;
  2382. // Atomic types are just wrappers; use the associations of the
  2383. // contained type.
  2384. case Type::Atomic:
  2385. T = cast<AtomicType>(T)->getValueType().getTypePtr();
  2386. continue;
  2387. case Type::Pipe:
  2388. T = cast<PipeType>(T)->getElementType().getTypePtr();
  2389. continue;
  2390. }
  2391. if (Queue.empty())
  2392. break;
  2393. T = Queue.pop_back_val();
  2394. }
  2395. }
  2396. /// Find the associated classes and namespaces for
  2397. /// argument-dependent lookup for a call with the given set of
  2398. /// arguments.
  2399. ///
  2400. /// This routine computes the sets of associated classes and associated
  2401. /// namespaces searched by argument-dependent lookup
  2402. /// (C++ [basic.lookup.argdep]) for a given set of arguments.
  2403. void Sema::FindAssociatedClassesAndNamespaces(
  2404. SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
  2405. AssociatedNamespaceSet &AssociatedNamespaces,
  2406. AssociatedClassSet &AssociatedClasses) {
  2407. AssociatedNamespaces.clear();
  2408. AssociatedClasses.clear();
  2409. AssociatedLookup Result(*this, InstantiationLoc,
  2410. AssociatedNamespaces, AssociatedClasses);
  2411. // C++ [basic.lookup.koenig]p2:
  2412. // For each argument type T in the function call, there is a set
  2413. // of zero or more associated namespaces and a set of zero or more
  2414. // associated classes to be considered. The sets of namespaces and
  2415. // classes is determined entirely by the types of the function
  2416. // arguments (and the namespace of any template template
  2417. // argument).
  2418. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  2419. Expr *Arg = Args[ArgIdx];
  2420. if (Arg->getType() != Context.OverloadTy) {
  2421. addAssociatedClassesAndNamespaces(Result, Arg->getType());
  2422. continue;
  2423. }
  2424. // [...] In addition, if the argument is the name or address of a
  2425. // set of overloaded functions and/or function templates, its
  2426. // associated classes and namespaces are the union of those
  2427. // associated with each of the members of the set: the namespace
  2428. // in which the function or function template is defined and the
  2429. // classes and namespaces associated with its (non-dependent)
  2430. // parameter types and return type.
  2431. OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
  2432. for (const NamedDecl *D : OE->decls()) {
  2433. // Look through any using declarations to find the underlying function.
  2434. const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
  2435. // Add the classes and namespaces associated with the parameter
  2436. // types and return type of this function.
  2437. addAssociatedClassesAndNamespaces(Result, FDecl->getType());
  2438. }
  2439. }
  2440. }
  2441. NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
  2442. SourceLocation Loc,
  2443. LookupNameKind NameKind,
  2444. RedeclarationKind Redecl) {
  2445. LookupResult R(*this, Name, Loc, NameKind, Redecl);
  2446. LookupName(R, S);
  2447. return R.getAsSingle<NamedDecl>();
  2448. }
  2449. /// Find the protocol with the given name, if any.
  2450. ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
  2451. SourceLocation IdLoc,
  2452. RedeclarationKind Redecl) {
  2453. Decl *D = LookupSingleName(TUScope, II, IdLoc,
  2454. LookupObjCProtocolName, Redecl);
  2455. return cast_or_null<ObjCProtocolDecl>(D);
  2456. }
  2457. void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
  2458. QualType T1, QualType T2,
  2459. UnresolvedSetImpl &Functions) {
  2460. // C++ [over.match.oper]p3:
  2461. // -- The set of non-member candidates is the result of the
  2462. // unqualified lookup of operator@ in the context of the
  2463. // expression according to the usual rules for name lookup in
  2464. // unqualified function calls (3.4.2) except that all member
  2465. // functions are ignored.
  2466. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  2467. LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
  2468. LookupName(Operators, S);
  2469. assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
  2470. Functions.append(Operators.begin(), Operators.end());
  2471. }
  2472. Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
  2473. CXXSpecialMember SM,
  2474. bool ConstArg,
  2475. bool VolatileArg,
  2476. bool RValueThis,
  2477. bool ConstThis,
  2478. bool VolatileThis) {
  2479. assert(CanDeclareSpecialMemberFunction(RD) &&
  2480. "doing special member lookup into record that isn't fully complete");
  2481. RD = RD->getDefinition();
  2482. if (RValueThis || ConstThis || VolatileThis)
  2483. assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
  2484. "constructors and destructors always have unqualified lvalue this");
  2485. if (ConstArg || VolatileArg)
  2486. assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
  2487. "parameter-less special members can't have qualified arguments");
  2488. // FIXME: Get the caller to pass in a location for the lookup.
  2489. SourceLocation LookupLoc = RD->getLocation();
  2490. llvm::FoldingSetNodeID ID;
  2491. ID.AddPointer(RD);
  2492. ID.AddInteger(SM);
  2493. ID.AddInteger(ConstArg);
  2494. ID.AddInteger(VolatileArg);
  2495. ID.AddInteger(RValueThis);
  2496. ID.AddInteger(ConstThis);
  2497. ID.AddInteger(VolatileThis);
  2498. void *InsertPoint;
  2499. SpecialMemberOverloadResultEntry *Result =
  2500. SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
  2501. // This was already cached
  2502. if (Result)
  2503. return *Result;
  2504. Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
  2505. Result = new (Result) SpecialMemberOverloadResultEntry(ID);
  2506. SpecialMemberCache.InsertNode(Result, InsertPoint);
  2507. if (SM == CXXDestructor) {
  2508. if (RD->needsImplicitDestructor())
  2509. DeclareImplicitDestructor(RD);
  2510. CXXDestructorDecl *DD = RD->getDestructor();
  2511. assert(DD && "record without a destructor");
  2512. Result->setMethod(DD);
  2513. Result->setKind(DD->isDeleted() ?
  2514. SpecialMemberOverloadResult::NoMemberOrDeleted :
  2515. SpecialMemberOverloadResult::Success);
  2516. return *Result;
  2517. }
  2518. // Prepare for overload resolution. Here we construct a synthetic argument
  2519. // if necessary and make sure that implicit functions are declared.
  2520. CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
  2521. DeclarationName Name;
  2522. Expr *Arg = nullptr;
  2523. unsigned NumArgs;
  2524. QualType ArgType = CanTy;
  2525. ExprValueKind VK = VK_LValue;
  2526. if (SM == CXXDefaultConstructor) {
  2527. Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
  2528. NumArgs = 0;
  2529. if (RD->needsImplicitDefaultConstructor())
  2530. DeclareImplicitDefaultConstructor(RD);
  2531. } else {
  2532. if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
  2533. Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
  2534. if (RD->needsImplicitCopyConstructor())
  2535. DeclareImplicitCopyConstructor(RD);
  2536. if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
  2537. DeclareImplicitMoveConstructor(RD);
  2538. } else {
  2539. Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  2540. if (RD->needsImplicitCopyAssignment())
  2541. DeclareImplicitCopyAssignment(RD);
  2542. if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
  2543. DeclareImplicitMoveAssignment(RD);
  2544. }
  2545. if (ConstArg)
  2546. ArgType.addConst();
  2547. if (VolatileArg)
  2548. ArgType.addVolatile();
  2549. // This isn't /really/ specified by the standard, but it's implied
  2550. // we should be working from an RValue in the case of move to ensure
  2551. // that we prefer to bind to rvalue references, and an LValue in the
  2552. // case of copy to ensure we don't bind to rvalue references.
  2553. // Possibly an XValue is actually correct in the case of move, but
  2554. // there is no semantic difference for class types in this restricted
  2555. // case.
  2556. if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
  2557. VK = VK_LValue;
  2558. else
  2559. VK = VK_RValue;
  2560. }
  2561. OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
  2562. if (SM != CXXDefaultConstructor) {
  2563. NumArgs = 1;
  2564. Arg = &FakeArg;
  2565. }
  2566. // Create the object argument
  2567. QualType ThisTy = CanTy;
  2568. if (ConstThis)
  2569. ThisTy.addConst();
  2570. if (VolatileThis)
  2571. ThisTy.addVolatile();
  2572. Expr::Classification Classification =
  2573. OpaqueValueExpr(LookupLoc, ThisTy,
  2574. RValueThis ? VK_RValue : VK_LValue).Classify(Context);
  2575. // Now we perform lookup on the name we computed earlier and do overload
  2576. // resolution. Lookup is only performed directly into the class since there
  2577. // will always be a (possibly implicit) declaration to shadow any others.
  2578. OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
  2579. DeclContext::lookup_result R = RD->lookup(Name);
  2580. if (R.empty()) {
  2581. // We might have no default constructor because we have a lambda's closure
  2582. // type, rather than because there's some other declared constructor.
  2583. // Every class has a copy/move constructor, copy/move assignment, and
  2584. // destructor.
  2585. assert(SM == CXXDefaultConstructor &&
  2586. "lookup for a constructor or assignment operator was empty");
  2587. Result->setMethod(nullptr);
  2588. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  2589. return *Result;
  2590. }
  2591. // Copy the candidates as our processing of them may load new declarations
  2592. // from an external source and invalidate lookup_result.
  2593. SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
  2594. for (NamedDecl *CandDecl : Candidates) {
  2595. if (CandDecl->isInvalidDecl())
  2596. continue;
  2597. DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
  2598. auto CtorInfo = getConstructorInfo(Cand);
  2599. if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
  2600. if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
  2601. AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
  2602. llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
  2603. else if (CtorInfo)
  2604. AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
  2605. llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
  2606. else
  2607. AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
  2608. true);
  2609. } else if (FunctionTemplateDecl *Tmpl =
  2610. dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
  2611. if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
  2612. AddMethodTemplateCandidate(
  2613. Tmpl, Cand, RD, nullptr, ThisTy, Classification,
  2614. llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
  2615. else if (CtorInfo)
  2616. AddTemplateOverloadCandidate(
  2617. CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
  2618. llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
  2619. else
  2620. AddTemplateOverloadCandidate(
  2621. Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
  2622. } else {
  2623. assert(isa<UsingDecl>(Cand.getDecl()) &&
  2624. "illegal Kind of operator = Decl");
  2625. }
  2626. }
  2627. OverloadCandidateSet::iterator Best;
  2628. switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
  2629. case OR_Success:
  2630. Result->setMethod(cast<CXXMethodDecl>(Best->Function));
  2631. Result->setKind(SpecialMemberOverloadResult::Success);
  2632. break;
  2633. case OR_Deleted:
  2634. Result->setMethod(cast<CXXMethodDecl>(Best->Function));
  2635. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  2636. break;
  2637. case OR_Ambiguous:
  2638. Result->setMethod(nullptr);
  2639. Result->setKind(SpecialMemberOverloadResult::Ambiguous);
  2640. break;
  2641. case OR_No_Viable_Function:
  2642. Result->setMethod(nullptr);
  2643. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  2644. break;
  2645. }
  2646. return *Result;
  2647. }
  2648. /// Look up the default constructor for the given class.
  2649. CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
  2650. SpecialMemberOverloadResult Result =
  2651. LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
  2652. false, false);
  2653. return cast_or_null<CXXConstructorDecl>(Result.getMethod());
  2654. }
  2655. /// Look up the copying constructor for the given class.
  2656. CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
  2657. unsigned Quals) {
  2658. assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2659. "non-const, non-volatile qualifiers for copy ctor arg");
  2660. SpecialMemberOverloadResult Result =
  2661. LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
  2662. Quals & Qualifiers::Volatile, false, false, false);
  2663. return cast_or_null<CXXConstructorDecl>(Result.getMethod());
  2664. }
  2665. /// Look up the moving constructor for the given class.
  2666. CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
  2667. unsigned Quals) {
  2668. SpecialMemberOverloadResult Result =
  2669. LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
  2670. Quals & Qualifiers::Volatile, false, false, false);
  2671. return cast_or_null<CXXConstructorDecl>(Result.getMethod());
  2672. }
  2673. /// Look up the constructors for the given class.
  2674. DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
  2675. // If the implicit constructors have not yet been declared, do so now.
  2676. if (CanDeclareSpecialMemberFunction(Class)) {
  2677. if (Class->needsImplicitDefaultConstructor())
  2678. DeclareImplicitDefaultConstructor(Class);
  2679. if (Class->needsImplicitCopyConstructor())
  2680. DeclareImplicitCopyConstructor(Class);
  2681. if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
  2682. DeclareImplicitMoveConstructor(Class);
  2683. }
  2684. CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
  2685. DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
  2686. return Class->lookup(Name);
  2687. }
  2688. /// Look up the copying assignment operator for the given class.
  2689. CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
  2690. unsigned Quals, bool RValueThis,
  2691. unsigned ThisQuals) {
  2692. assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2693. "non-const, non-volatile qualifiers for copy assignment arg");
  2694. assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2695. "non-const, non-volatile qualifiers for copy assignment this");
  2696. SpecialMemberOverloadResult Result =
  2697. LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
  2698. Quals & Qualifiers::Volatile, RValueThis,
  2699. ThisQuals & Qualifiers::Const,
  2700. ThisQuals & Qualifiers::Volatile);
  2701. return Result.getMethod();
  2702. }
  2703. /// Look up the moving assignment operator for the given class.
  2704. CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
  2705. unsigned Quals,
  2706. bool RValueThis,
  2707. unsigned ThisQuals) {
  2708. assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2709. "non-const, non-volatile qualifiers for copy assignment this");
  2710. SpecialMemberOverloadResult Result =
  2711. LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
  2712. Quals & Qualifiers::Volatile, RValueThis,
  2713. ThisQuals & Qualifiers::Const,
  2714. ThisQuals & Qualifiers::Volatile);
  2715. return Result.getMethod();
  2716. }
  2717. /// Look for the destructor of the given class.
  2718. ///
  2719. /// During semantic analysis, this routine should be used in lieu of
  2720. /// CXXRecordDecl::getDestructor().
  2721. ///
  2722. /// \returns The destructor for this class.
  2723. CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
  2724. return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
  2725. false, false, false,
  2726. false, false).getMethod());
  2727. }
  2728. /// LookupLiteralOperator - Determine which literal operator should be used for
  2729. /// a user-defined literal, per C++11 [lex.ext].
  2730. ///
  2731. /// Normal overload resolution is not used to select which literal operator to
  2732. /// call for a user-defined literal. Look up the provided literal operator name,
  2733. /// and filter the results to the appropriate set for the given argument types.
  2734. Sema::LiteralOperatorLookupResult
  2735. Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
  2736. ArrayRef<QualType> ArgTys,
  2737. bool AllowRaw, bool AllowTemplate,
  2738. bool AllowStringTemplate, bool DiagnoseMissing) {
  2739. LookupName(R, S);
  2740. assert(R.getResultKind() != LookupResult::Ambiguous &&
  2741. "literal operator lookup can't be ambiguous");
  2742. // Filter the lookup results appropriately.
  2743. LookupResult::Filter F = R.makeFilter();
  2744. bool FoundRaw = false;
  2745. bool FoundTemplate = false;
  2746. bool FoundStringTemplate = false;
  2747. bool FoundExactMatch = false;
  2748. while (F.hasNext()) {
  2749. Decl *D = F.next();
  2750. if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
  2751. D = USD->getTargetDecl();
  2752. // If the declaration we found is invalid, skip it.
  2753. if (D->isInvalidDecl()) {
  2754. F.erase();
  2755. continue;
  2756. }
  2757. bool IsRaw = false;
  2758. bool IsTemplate = false;
  2759. bool IsStringTemplate = false;
  2760. bool IsExactMatch = false;
  2761. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2762. if (FD->getNumParams() == 1 &&
  2763. FD->getParamDecl(0)->getType()->getAs<PointerType>())
  2764. IsRaw = true;
  2765. else if (FD->getNumParams() == ArgTys.size()) {
  2766. IsExactMatch = true;
  2767. for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
  2768. QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
  2769. if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
  2770. IsExactMatch = false;
  2771. break;
  2772. }
  2773. }
  2774. }
  2775. }
  2776. if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
  2777. TemplateParameterList *Params = FD->getTemplateParameters();
  2778. if (Params->size() == 1)
  2779. IsTemplate = true;
  2780. else
  2781. IsStringTemplate = true;
  2782. }
  2783. if (IsExactMatch) {
  2784. FoundExactMatch = true;
  2785. AllowRaw = false;
  2786. AllowTemplate = false;
  2787. AllowStringTemplate = false;
  2788. if (FoundRaw || FoundTemplate || FoundStringTemplate) {
  2789. // Go through again and remove the raw and template decls we've
  2790. // already found.
  2791. F.restart();
  2792. FoundRaw = FoundTemplate = FoundStringTemplate = false;
  2793. }
  2794. } else if (AllowRaw && IsRaw) {
  2795. FoundRaw = true;
  2796. } else if (AllowTemplate && IsTemplate) {
  2797. FoundTemplate = true;
  2798. } else if (AllowStringTemplate && IsStringTemplate) {
  2799. FoundStringTemplate = true;
  2800. } else {
  2801. F.erase();
  2802. }
  2803. }
  2804. F.done();
  2805. // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
  2806. // parameter type, that is used in preference to a raw literal operator
  2807. // or literal operator template.
  2808. if (FoundExactMatch)
  2809. return LOLR_Cooked;
  2810. // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
  2811. // operator template, but not both.
  2812. if (FoundRaw && FoundTemplate) {
  2813. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  2814. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  2815. NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
  2816. return LOLR_Error;
  2817. }
  2818. if (FoundRaw)
  2819. return LOLR_Raw;
  2820. if (FoundTemplate)
  2821. return LOLR_Template;
  2822. if (FoundStringTemplate)
  2823. return LOLR_StringTemplate;
  2824. // Didn't find anything we could use.
  2825. if (DiagnoseMissing) {
  2826. Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
  2827. << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
  2828. << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
  2829. << (AllowTemplate || AllowStringTemplate);
  2830. return LOLR_Error;
  2831. }
  2832. return LOLR_ErrorNoDiagnostic;
  2833. }
  2834. void ADLResult::insert(NamedDecl *New) {
  2835. NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
  2836. // If we haven't yet seen a decl for this key, or the last decl
  2837. // was exactly this one, we're done.
  2838. if (Old == nullptr || Old == New) {
  2839. Old = New;
  2840. return;
  2841. }
  2842. // Otherwise, decide which is a more recent redeclaration.
  2843. FunctionDecl *OldFD = Old->getAsFunction();
  2844. FunctionDecl *NewFD = New->getAsFunction();
  2845. FunctionDecl *Cursor = NewFD;
  2846. while (true) {
  2847. Cursor = Cursor->getPreviousDecl();
  2848. // If we got to the end without finding OldFD, OldFD is the newer
  2849. // declaration; leave things as they are.
  2850. if (!Cursor) return;
  2851. // If we do find OldFD, then NewFD is newer.
  2852. if (Cursor == OldFD) break;
  2853. // Otherwise, keep looking.
  2854. }
  2855. Old = New;
  2856. }
  2857. void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
  2858. ArrayRef<Expr *> Args, ADLResult &Result) {
  2859. // Find all of the associated namespaces and classes based on the
  2860. // arguments we have.
  2861. AssociatedNamespaceSet AssociatedNamespaces;
  2862. AssociatedClassSet AssociatedClasses;
  2863. FindAssociatedClassesAndNamespaces(Loc, Args,
  2864. AssociatedNamespaces,
  2865. AssociatedClasses);
  2866. // C++ [basic.lookup.argdep]p3:
  2867. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  2868. // and let Y be the lookup set produced by argument dependent
  2869. // lookup (defined as follows). If X contains [...] then Y is
  2870. // empty. Otherwise Y is the set of declarations found in the
  2871. // namespaces associated with the argument types as described
  2872. // below. The set of declarations found by the lookup of the name
  2873. // is the union of X and Y.
  2874. //
  2875. // Here, we compute Y and add its members to the overloaded
  2876. // candidate set.
  2877. for (auto *NS : AssociatedNamespaces) {
  2878. // When considering an associated namespace, the lookup is the
  2879. // same as the lookup performed when the associated namespace is
  2880. // used as a qualifier (3.4.3.2) except that:
  2881. //
  2882. // -- Any using-directives in the associated namespace are
  2883. // ignored.
  2884. //
  2885. // -- Any namespace-scope friend functions declared in
  2886. // associated classes are visible within their respective
  2887. // namespaces even if they are not visible during an ordinary
  2888. // lookup (11.4).
  2889. DeclContext::lookup_result R = NS->lookup(Name);
  2890. for (auto *D : R) {
  2891. auto *Underlying = D;
  2892. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  2893. Underlying = USD->getTargetDecl();
  2894. if (!isa<FunctionDecl>(Underlying) &&
  2895. !isa<FunctionTemplateDecl>(Underlying))
  2896. continue;
  2897. // The declaration is visible to argument-dependent lookup if either
  2898. // it's ordinarily visible or declared as a friend in an associated
  2899. // class.
  2900. bool Visible = false;
  2901. for (D = D->getMostRecentDecl(); D;
  2902. D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
  2903. if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
  2904. if (isVisible(D)) {
  2905. Visible = true;
  2906. break;
  2907. }
  2908. } else if (D->getFriendObjectKind()) {
  2909. auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
  2910. if (AssociatedClasses.count(RD) && isVisible(D)) {
  2911. Visible = true;
  2912. break;
  2913. }
  2914. }
  2915. }
  2916. // FIXME: Preserve D as the FoundDecl.
  2917. if (Visible)
  2918. Result.insert(Underlying);
  2919. }
  2920. }
  2921. }
  2922. //----------------------------------------------------------------------------
  2923. // Search for all visible declarations.
  2924. //----------------------------------------------------------------------------
  2925. VisibleDeclConsumer::~VisibleDeclConsumer() { }
  2926. bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
  2927. namespace {
  2928. class ShadowContextRAII;
  2929. class VisibleDeclsRecord {
  2930. public:
  2931. /// An entry in the shadow map, which is optimized to store a
  2932. /// single declaration (the common case) but can also store a list
  2933. /// of declarations.
  2934. typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
  2935. private:
  2936. /// A mapping from declaration names to the declarations that have
  2937. /// this name within a particular scope.
  2938. typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
  2939. /// A list of shadow maps, which is used to model name hiding.
  2940. std::list<ShadowMap> ShadowMaps;
  2941. /// The declaration contexts we have already visited.
  2942. llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
  2943. friend class ShadowContextRAII;
  2944. public:
  2945. /// Determine whether we have already visited this context
  2946. /// (and, if not, note that we are going to visit that context now).
  2947. bool visitedContext(DeclContext *Ctx) {
  2948. return !VisitedContexts.insert(Ctx).second;
  2949. }
  2950. bool alreadyVisitedContext(DeclContext *Ctx) {
  2951. return VisitedContexts.count(Ctx);
  2952. }
  2953. /// Determine whether the given declaration is hidden in the
  2954. /// current scope.
  2955. ///
  2956. /// \returns the declaration that hides the given declaration, or
  2957. /// NULL if no such declaration exists.
  2958. NamedDecl *checkHidden(NamedDecl *ND);
  2959. /// Add a declaration to the current shadow map.
  2960. void add(NamedDecl *ND) {
  2961. ShadowMaps.back()[ND->getDeclName()].push_back(ND);
  2962. }
  2963. };
  2964. /// RAII object that records when we've entered a shadow context.
  2965. class ShadowContextRAII {
  2966. VisibleDeclsRecord &Visible;
  2967. typedef VisibleDeclsRecord::ShadowMap ShadowMap;
  2968. public:
  2969. ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
  2970. Visible.ShadowMaps.emplace_back();
  2971. }
  2972. ~ShadowContextRAII() {
  2973. Visible.ShadowMaps.pop_back();
  2974. }
  2975. };
  2976. } // end anonymous namespace
  2977. NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
  2978. unsigned IDNS = ND->getIdentifierNamespace();
  2979. std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
  2980. for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
  2981. SM != SMEnd; ++SM) {
  2982. ShadowMap::iterator Pos = SM->find(ND->getDeclName());
  2983. if (Pos == SM->end())
  2984. continue;
  2985. for (auto *D : Pos->second) {
  2986. // A tag declaration does not hide a non-tag declaration.
  2987. if (D->hasTagIdentifierNamespace() &&
  2988. (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
  2989. Decl::IDNS_ObjCProtocol)))
  2990. continue;
  2991. // Protocols are in distinct namespaces from everything else.
  2992. if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
  2993. || (IDNS & Decl::IDNS_ObjCProtocol)) &&
  2994. D->getIdentifierNamespace() != IDNS)
  2995. continue;
  2996. // Functions and function templates in the same scope overload
  2997. // rather than hide. FIXME: Look for hiding based on function
  2998. // signatures!
  2999. if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
  3000. ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
  3001. SM == ShadowMaps.rbegin())
  3002. continue;
  3003. // A shadow declaration that's created by a resolved using declaration
  3004. // is not hidden by the same using declaration.
  3005. if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
  3006. cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
  3007. continue;
  3008. // We've found a declaration that hides this one.
  3009. return D;
  3010. }
  3011. }
  3012. return nullptr;
  3013. }
  3014. static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
  3015. bool QualifiedNameLookup,
  3016. bool InBaseClass,
  3017. VisibleDeclConsumer &Consumer,
  3018. VisibleDeclsRecord &Visited,
  3019. bool IncludeDependentBases,
  3020. bool LoadExternal) {
  3021. if (!Ctx)
  3022. return;
  3023. // Make sure we don't visit the same context twice.
  3024. if (Visited.visitedContext(Ctx->getPrimaryContext()))
  3025. return;
  3026. Consumer.EnteredContext(Ctx);
  3027. // Outside C++, lookup results for the TU live on identifiers.
  3028. if (isa<TranslationUnitDecl>(Ctx) &&
  3029. !Result.getSema().getLangOpts().CPlusPlus) {
  3030. auto &S = Result.getSema();
  3031. auto &Idents = S.Context.Idents;
  3032. // Ensure all external identifiers are in the identifier table.
  3033. if (LoadExternal)
  3034. if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
  3035. std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
  3036. for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
  3037. Idents.get(Name);
  3038. }
  3039. // Walk all lookup results in the TU for each identifier.
  3040. for (const auto &Ident : Idents) {
  3041. for (auto I = S.IdResolver.begin(Ident.getValue()),
  3042. E = S.IdResolver.end();
  3043. I != E; ++I) {
  3044. if (S.IdResolver.isDeclInScope(*I, Ctx)) {
  3045. if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
  3046. Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
  3047. Visited.add(ND);
  3048. }
  3049. }
  3050. }
  3051. }
  3052. return;
  3053. }
  3054. if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
  3055. Result.getSema().ForceDeclarationOfImplicitMembers(Class);
  3056. // We sometimes skip loading namespace-level results (they tend to be huge).
  3057. bool Load = LoadExternal ||
  3058. !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
  3059. // Enumerate all of the results in this context.
  3060. for (DeclContextLookupResult R :
  3061. Load ? Ctx->lookups()
  3062. : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
  3063. for (auto *D : R) {
  3064. if (auto *ND = Result.getAcceptableDecl(D)) {
  3065. Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
  3066. Visited.add(ND);
  3067. }
  3068. }
  3069. }
  3070. // Traverse using directives for qualified name lookup.
  3071. if (QualifiedNameLookup) {
  3072. ShadowContextRAII Shadow(Visited);
  3073. for (auto I : Ctx->using_directives()) {
  3074. if (!Result.getSema().isVisible(I))
  3075. continue;
  3076. LookupVisibleDecls(I->getNominatedNamespace(), Result,
  3077. QualifiedNameLookup, InBaseClass, Consumer, Visited,
  3078. IncludeDependentBases, LoadExternal);
  3079. }
  3080. }
  3081. // Traverse the contexts of inherited C++ classes.
  3082. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
  3083. if (!Record->hasDefinition())
  3084. return;
  3085. for (const auto &B : Record->bases()) {
  3086. QualType BaseType = B.getType();
  3087. RecordDecl *RD;
  3088. if (BaseType->isDependentType()) {
  3089. if (!IncludeDependentBases) {
  3090. // Don't look into dependent bases, because name lookup can't look
  3091. // there anyway.
  3092. continue;
  3093. }
  3094. const auto *TST = BaseType->getAs<TemplateSpecializationType>();
  3095. if (!TST)
  3096. continue;
  3097. TemplateName TN = TST->getTemplateName();
  3098. const auto *TD =
  3099. dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
  3100. if (!TD)
  3101. continue;
  3102. RD = TD->getTemplatedDecl();
  3103. } else {
  3104. const auto *Record = BaseType->getAs<RecordType>();
  3105. if (!Record)
  3106. continue;
  3107. RD = Record->getDecl();
  3108. }
  3109. // FIXME: It would be nice to be able to determine whether referencing
  3110. // a particular member would be ambiguous. For example, given
  3111. //
  3112. // struct A { int member; };
  3113. // struct B { int member; };
  3114. // struct C : A, B { };
  3115. //
  3116. // void f(C *c) { c->### }
  3117. //
  3118. // accessing 'member' would result in an ambiguity. However, we
  3119. // could be smart enough to qualify the member with the base
  3120. // class, e.g.,
  3121. //
  3122. // c->B::member
  3123. //
  3124. // or
  3125. //
  3126. // c->A::member
  3127. // Find results in this base class (and its bases).
  3128. ShadowContextRAII Shadow(Visited);
  3129. LookupVisibleDecls(RD, Result, QualifiedNameLookup, /*InBaseClass=*/true,
  3130. Consumer, Visited, IncludeDependentBases,
  3131. LoadExternal);
  3132. }
  3133. }
  3134. // Traverse the contexts of Objective-C classes.
  3135. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
  3136. // Traverse categories.
  3137. for (auto *Cat : IFace->visible_categories()) {
  3138. ShadowContextRAII Shadow(Visited);
  3139. LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer,
  3140. Visited, IncludeDependentBases, LoadExternal);
  3141. }
  3142. // Traverse protocols.
  3143. for (auto *I : IFace->all_referenced_protocols()) {
  3144. ShadowContextRAII Shadow(Visited);
  3145. LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
  3146. Visited, IncludeDependentBases, LoadExternal);
  3147. }
  3148. // Traverse the superclass.
  3149. if (IFace->getSuperClass()) {
  3150. ShadowContextRAII Shadow(Visited);
  3151. LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
  3152. true, Consumer, Visited, IncludeDependentBases,
  3153. LoadExternal);
  3154. }
  3155. // If there is an implementation, traverse it. We do this to find
  3156. // synthesized ivars.
  3157. if (IFace->getImplementation()) {
  3158. ShadowContextRAII Shadow(Visited);
  3159. LookupVisibleDecls(IFace->getImplementation(), Result,
  3160. QualifiedNameLookup, InBaseClass, Consumer, Visited,
  3161. IncludeDependentBases, LoadExternal);
  3162. }
  3163. } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
  3164. for (auto *I : Protocol->protocols()) {
  3165. ShadowContextRAII Shadow(Visited);
  3166. LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
  3167. Visited, IncludeDependentBases, LoadExternal);
  3168. }
  3169. } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
  3170. for (auto *I : Category->protocols()) {
  3171. ShadowContextRAII Shadow(Visited);
  3172. LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
  3173. Visited, IncludeDependentBases, LoadExternal);
  3174. }
  3175. // If there is an implementation, traverse it.
  3176. if (Category->getImplementation()) {
  3177. ShadowContextRAII Shadow(Visited);
  3178. LookupVisibleDecls(Category->getImplementation(), Result,
  3179. QualifiedNameLookup, true, Consumer, Visited,
  3180. IncludeDependentBases, LoadExternal);
  3181. }
  3182. }
  3183. }
  3184. static void LookupVisibleDecls(Scope *S, LookupResult &Result,
  3185. UnqualUsingDirectiveSet &UDirs,
  3186. VisibleDeclConsumer &Consumer,
  3187. VisibleDeclsRecord &Visited,
  3188. bool LoadExternal) {
  3189. if (!S)
  3190. return;
  3191. if (!S->getEntity() ||
  3192. (!S->getParent() &&
  3193. !Visited.alreadyVisitedContext(S->getEntity())) ||
  3194. (S->getEntity())->isFunctionOrMethod()) {
  3195. FindLocalExternScope FindLocals(Result);
  3196. // Walk through the declarations in this Scope. The consumer might add new
  3197. // decls to the scope as part of deserialization, so make a copy first.
  3198. SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
  3199. for (Decl *D : ScopeDecls) {
  3200. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  3201. if ((ND = Result.getAcceptableDecl(ND))) {
  3202. Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
  3203. Visited.add(ND);
  3204. }
  3205. }
  3206. }
  3207. // FIXME: C++ [temp.local]p8
  3208. DeclContext *Entity = nullptr;
  3209. if (S->getEntity()) {
  3210. // Look into this scope's declaration context, along with any of its
  3211. // parent lookup contexts (e.g., enclosing classes), up to the point
  3212. // where we hit the context stored in the next outer scope.
  3213. Entity = S->getEntity();
  3214. DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
  3215. for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
  3216. Ctx = Ctx->getLookupParent()) {
  3217. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
  3218. if (Method->isInstanceMethod()) {
  3219. // For instance methods, look for ivars in the method's interface.
  3220. LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
  3221. Result.getNameLoc(), Sema::LookupMemberName);
  3222. if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
  3223. LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
  3224. /*InBaseClass=*/false, Consumer, Visited,
  3225. /*IncludeDependentBases=*/false, LoadExternal);
  3226. }
  3227. }
  3228. // We've already performed all of the name lookup that we need
  3229. // to for Objective-C methods; the next context will be the
  3230. // outer scope.
  3231. break;
  3232. }
  3233. if (Ctx->isFunctionOrMethod())
  3234. continue;
  3235. LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
  3236. /*InBaseClass=*/false, Consumer, Visited,
  3237. /*IncludeDependentBases=*/false, LoadExternal);
  3238. }
  3239. } else if (!S->getParent()) {
  3240. // Look into the translation unit scope. We walk through the translation
  3241. // unit's declaration context, because the Scope itself won't have all of
  3242. // the declarations if we loaded a precompiled header.
  3243. // FIXME: We would like the translation unit's Scope object to point to the
  3244. // translation unit, so we don't need this special "if" branch. However,
  3245. // doing so would force the normal C++ name-lookup code to look into the
  3246. // translation unit decl when the IdentifierInfo chains would suffice.
  3247. // Once we fix that problem (which is part of a more general "don't look
  3248. // in DeclContexts unless we have to" optimization), we can eliminate this.
  3249. Entity = Result.getSema().Context.getTranslationUnitDecl();
  3250. LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
  3251. /*InBaseClass=*/false, Consumer, Visited,
  3252. /*IncludeDependentBases=*/false, LoadExternal);
  3253. }
  3254. if (Entity) {
  3255. // Lookup visible declarations in any namespaces found by using
  3256. // directives.
  3257. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
  3258. LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
  3259. Result, /*QualifiedNameLookup=*/false,
  3260. /*InBaseClass=*/false, Consumer, Visited,
  3261. /*IncludeDependentBases=*/false, LoadExternal);
  3262. }
  3263. // Lookup names in the parent scope.
  3264. ShadowContextRAII Shadow(Visited);
  3265. LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited,
  3266. LoadExternal);
  3267. }
  3268. void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
  3269. VisibleDeclConsumer &Consumer,
  3270. bool IncludeGlobalScope, bool LoadExternal) {
  3271. // Determine the set of using directives available during
  3272. // unqualified name lookup.
  3273. Scope *Initial = S;
  3274. UnqualUsingDirectiveSet UDirs(*this);
  3275. if (getLangOpts().CPlusPlus) {
  3276. // Find the first namespace or translation-unit scope.
  3277. while (S && !isNamespaceOrTranslationUnitScope(S))
  3278. S = S->getParent();
  3279. UDirs.visitScopeChain(Initial, S);
  3280. }
  3281. UDirs.done();
  3282. // Look for visible declarations.
  3283. LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
  3284. Result.setAllowHidden(Consumer.includeHiddenDecls());
  3285. VisibleDeclsRecord Visited;
  3286. if (!IncludeGlobalScope)
  3287. Visited.visitedContext(Context.getTranslationUnitDecl());
  3288. ShadowContextRAII Shadow(Visited);
  3289. ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal);
  3290. }
  3291. void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
  3292. VisibleDeclConsumer &Consumer,
  3293. bool IncludeGlobalScope,
  3294. bool IncludeDependentBases, bool LoadExternal) {
  3295. LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
  3296. Result.setAllowHidden(Consumer.includeHiddenDecls());
  3297. VisibleDeclsRecord Visited;
  3298. if (!IncludeGlobalScope)
  3299. Visited.visitedContext(Context.getTranslationUnitDecl());
  3300. ShadowContextRAII Shadow(Visited);
  3301. ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
  3302. /*InBaseClass=*/false, Consumer, Visited,
  3303. IncludeDependentBases, LoadExternal);
  3304. }
  3305. /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
  3306. /// If GnuLabelLoc is a valid source location, then this is a definition
  3307. /// of an __label__ label name, otherwise it is a normal label definition
  3308. /// or use.
  3309. LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
  3310. SourceLocation GnuLabelLoc) {
  3311. // Do a lookup to see if we have a label with this name already.
  3312. NamedDecl *Res = nullptr;
  3313. if (GnuLabelLoc.isValid()) {
  3314. // Local label definitions always shadow existing labels.
  3315. Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
  3316. Scope *S = CurScope;
  3317. PushOnScopeChains(Res, S, true);
  3318. return cast<LabelDecl>(Res);
  3319. }
  3320. // Not a GNU local label.
  3321. Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
  3322. // If we found a label, check to see if it is in the same context as us.
  3323. // When in a Block, we don't want to reuse a label in an enclosing function.
  3324. if (Res && Res->getDeclContext() != CurContext)
  3325. Res = nullptr;
  3326. if (!Res) {
  3327. // If not forward referenced or defined already, create the backing decl.
  3328. Res = LabelDecl::Create(Context, CurContext, Loc, II);
  3329. Scope *S = CurScope->getFnParent();
  3330. assert(S && "Not in a function?");
  3331. PushOnScopeChains(Res, S, true);
  3332. }
  3333. return cast<LabelDecl>(Res);
  3334. }
  3335. //===----------------------------------------------------------------------===//
  3336. // Typo correction
  3337. //===----------------------------------------------------------------------===//
  3338. static bool isCandidateViable(CorrectionCandidateCallback &CCC,
  3339. TypoCorrection &Candidate) {
  3340. Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
  3341. return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
  3342. }
  3343. static void LookupPotentialTypoResult(Sema &SemaRef,
  3344. LookupResult &Res,
  3345. IdentifierInfo *Name,
  3346. Scope *S, CXXScopeSpec *SS,
  3347. DeclContext *MemberContext,
  3348. bool EnteringContext,
  3349. bool isObjCIvarLookup,
  3350. bool FindHidden);
  3351. /// Check whether the declarations found for a typo correction are
  3352. /// visible. Set the correction's RequiresImport flag to true if none of the
  3353. /// declarations are visible, false otherwise.
  3354. static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
  3355. TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
  3356. for (/**/; DI != DE; ++DI)
  3357. if (!LookupResult::isVisible(SemaRef, *DI))
  3358. break;
  3359. // No filtering needed if all decls are visible.
  3360. if (DI == DE) {
  3361. TC.setRequiresImport(false);
  3362. return;
  3363. }
  3364. llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
  3365. bool AnyVisibleDecls = !NewDecls.empty();
  3366. for (/**/; DI != DE; ++DI) {
  3367. if (LookupResult::isVisible(SemaRef, *DI)) {
  3368. if (!AnyVisibleDecls) {
  3369. // Found a visible decl, discard all hidden ones.
  3370. AnyVisibleDecls = true;
  3371. NewDecls.clear();
  3372. }
  3373. NewDecls.push_back(*DI);
  3374. } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
  3375. NewDecls.push_back(*DI);
  3376. }
  3377. if (NewDecls.empty())
  3378. TC = TypoCorrection();
  3379. else {
  3380. TC.setCorrectionDecls(NewDecls);
  3381. TC.setRequiresImport(!AnyVisibleDecls);
  3382. }
  3383. }
  3384. // Fill the supplied vector with the IdentifierInfo pointers for each piece of
  3385. // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
  3386. // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
  3387. static void getNestedNameSpecifierIdentifiers(
  3388. NestedNameSpecifier *NNS,
  3389. SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
  3390. if (NestedNameSpecifier *Prefix = NNS->getPrefix())
  3391. getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
  3392. else
  3393. Identifiers.clear();
  3394. const IdentifierInfo *II = nullptr;
  3395. switch (NNS->getKind()) {
  3396. case NestedNameSpecifier::Identifier:
  3397. II = NNS->getAsIdentifier();
  3398. break;
  3399. case NestedNameSpecifier::Namespace:
  3400. if (NNS->getAsNamespace()->isAnonymousNamespace())
  3401. return;
  3402. II = NNS->getAsNamespace()->getIdentifier();
  3403. break;
  3404. case NestedNameSpecifier::NamespaceAlias:
  3405. II = NNS->getAsNamespaceAlias()->getIdentifier();
  3406. break;
  3407. case NestedNameSpecifier::TypeSpecWithTemplate:
  3408. case NestedNameSpecifier::TypeSpec:
  3409. II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
  3410. break;
  3411. case NestedNameSpecifier::Global:
  3412. case NestedNameSpecifier::Super:
  3413. return;
  3414. }
  3415. if (II)
  3416. Identifiers.push_back(II);
  3417. }
  3418. void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
  3419. DeclContext *Ctx, bool InBaseClass) {
  3420. // Don't consider hidden names for typo correction.
  3421. if (Hiding)
  3422. return;
  3423. // Only consider entities with identifiers for names, ignoring
  3424. // special names (constructors, overloaded operators, selectors,
  3425. // etc.).
  3426. IdentifierInfo *Name = ND->getIdentifier();
  3427. if (!Name)
  3428. return;
  3429. // Only consider visible declarations and declarations from modules with
  3430. // names that exactly match.
  3431. if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
  3432. return;
  3433. FoundName(Name->getName());
  3434. }
  3435. void TypoCorrectionConsumer::FoundName(StringRef Name) {
  3436. // Compute the edit distance between the typo and the name of this
  3437. // entity, and add the identifier to the list of results.
  3438. addName(Name, nullptr);
  3439. }
  3440. void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
  3441. // Compute the edit distance between the typo and this keyword,
  3442. // and add the keyword to the list of results.
  3443. addName(Keyword, nullptr, nullptr, true);
  3444. }
  3445. void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
  3446. NestedNameSpecifier *NNS, bool isKeyword) {
  3447. // Use a simple length-based heuristic to determine the minimum possible
  3448. // edit distance. If the minimum isn't good enough, bail out early.
  3449. StringRef TypoStr = Typo->getName();
  3450. unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
  3451. if (MinED && TypoStr.size() / MinED < 3)
  3452. return;
  3453. // Compute an upper bound on the allowable edit distance, so that the
  3454. // edit-distance algorithm can short-circuit.
  3455. unsigned UpperBound = (TypoStr.size() + 2) / 3;
  3456. unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
  3457. if (ED > UpperBound) return;
  3458. TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
  3459. if (isKeyword) TC.makeKeyword();
  3460. TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
  3461. addCorrection(TC);
  3462. }
  3463. static const unsigned MaxTypoDistanceResultSets = 5;
  3464. void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
  3465. StringRef TypoStr = Typo->getName();
  3466. StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
  3467. // For very short typos, ignore potential corrections that have a different
  3468. // base identifier from the typo or which have a normalized edit distance
  3469. // longer than the typo itself.
  3470. if (TypoStr.size() < 3 &&
  3471. (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
  3472. return;
  3473. // If the correction is resolved but is not viable, ignore it.
  3474. if (Correction.isResolved()) {
  3475. checkCorrectionVisibility(SemaRef, Correction);
  3476. if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
  3477. return;
  3478. }
  3479. TypoResultList &CList =
  3480. CorrectionResults[Correction.getEditDistance(false)][Name];
  3481. if (!CList.empty() && !CList.back().isResolved())
  3482. CList.pop_back();
  3483. if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
  3484. std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
  3485. for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
  3486. RI != RIEnd; ++RI) {
  3487. // If the Correction refers to a decl already in the result list,
  3488. // replace the existing result if the string representation of Correction
  3489. // comes before the current result alphabetically, then stop as there is
  3490. // nothing more to be done to add Correction to the candidate set.
  3491. if (RI->getCorrectionDecl() == NewND) {
  3492. if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
  3493. *RI = Correction;
  3494. return;
  3495. }
  3496. }
  3497. }
  3498. if (CList.empty() || Correction.isResolved())
  3499. CList.push_back(Correction);
  3500. while (CorrectionResults.size() > MaxTypoDistanceResultSets)
  3501. CorrectionResults.erase(std::prev(CorrectionResults.end()));
  3502. }
  3503. void TypoCorrectionConsumer::addNamespaces(
  3504. const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
  3505. SearchNamespaces = true;
  3506. for (auto KNPair : KnownNamespaces)
  3507. Namespaces.addNameSpecifier(KNPair.first);
  3508. bool SSIsTemplate = false;
  3509. if (NestedNameSpecifier *NNS =
  3510. (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
  3511. if (const Type *T = NNS->getAsType())
  3512. SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
  3513. }
  3514. // Do not transform this into an iterator-based loop. The loop body can
  3515. // trigger the creation of further types (through lazy deserialization) and
  3516. // invalid iterators into this list.
  3517. auto &Types = SemaRef.getASTContext().getTypes();
  3518. for (unsigned I = 0; I != Types.size(); ++I) {
  3519. const auto *TI = Types[I];
  3520. if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
  3521. CD = CD->getCanonicalDecl();
  3522. if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
  3523. !CD->isUnion() && CD->getIdentifier() &&
  3524. (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
  3525. (CD->isBeingDefined() || CD->isCompleteDefinition()))
  3526. Namespaces.addNameSpecifier(CD);
  3527. }
  3528. }
  3529. }
  3530. const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
  3531. if (++CurrentTCIndex < ValidatedCorrections.size())
  3532. return ValidatedCorrections[CurrentTCIndex];
  3533. CurrentTCIndex = ValidatedCorrections.size();
  3534. while (!CorrectionResults.empty()) {
  3535. auto DI = CorrectionResults.begin();
  3536. if (DI->second.empty()) {
  3537. CorrectionResults.erase(DI);
  3538. continue;
  3539. }
  3540. auto RI = DI->second.begin();
  3541. if (RI->second.empty()) {
  3542. DI->second.erase(RI);
  3543. performQualifiedLookups();
  3544. continue;
  3545. }
  3546. TypoCorrection TC = RI->second.pop_back_val();
  3547. if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
  3548. ValidatedCorrections.push_back(TC);
  3549. return ValidatedCorrections[CurrentTCIndex];
  3550. }
  3551. }
  3552. return ValidatedCorrections[0]; // The empty correction.
  3553. }
  3554. bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
  3555. IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
  3556. DeclContext *TempMemberContext = MemberContext;
  3557. CXXScopeSpec *TempSS = SS.get();
  3558. retry_lookup:
  3559. LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
  3560. EnteringContext,
  3561. CorrectionValidator->IsObjCIvarLookup,
  3562. Name == Typo && !Candidate.WillReplaceSpecifier());
  3563. switch (Result.getResultKind()) {
  3564. case LookupResult::NotFound:
  3565. case LookupResult::NotFoundInCurrentInstantiation:
  3566. case LookupResult::FoundUnresolvedValue:
  3567. if (TempSS) {
  3568. // Immediately retry the lookup without the given CXXScopeSpec
  3569. TempSS = nullptr;
  3570. Candidate.WillReplaceSpecifier(true);
  3571. goto retry_lookup;
  3572. }
  3573. if (TempMemberContext) {
  3574. if (SS && !TempSS)
  3575. TempSS = SS.get();
  3576. TempMemberContext = nullptr;
  3577. goto retry_lookup;
  3578. }
  3579. if (SearchNamespaces)
  3580. QualifiedResults.push_back(Candidate);
  3581. break;
  3582. case LookupResult::Ambiguous:
  3583. // We don't deal with ambiguities.
  3584. break;
  3585. case LookupResult::Found:
  3586. case LookupResult::FoundOverloaded:
  3587. // Store all of the Decls for overloaded symbols
  3588. for (auto *TRD : Result)
  3589. Candidate.addCorrectionDecl(TRD);
  3590. checkCorrectionVisibility(SemaRef, Candidate);
  3591. if (!isCandidateViable(*CorrectionValidator, Candidate)) {
  3592. if (SearchNamespaces)
  3593. QualifiedResults.push_back(Candidate);
  3594. break;
  3595. }
  3596. Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
  3597. return true;
  3598. }
  3599. return false;
  3600. }
  3601. void TypoCorrectionConsumer::performQualifiedLookups() {
  3602. unsigned TypoLen = Typo->getName().size();
  3603. for (const TypoCorrection &QR : QualifiedResults) {
  3604. for (const auto &NSI : Namespaces) {
  3605. DeclContext *Ctx = NSI.DeclCtx;
  3606. const Type *NSType = NSI.NameSpecifier->getAsType();
  3607. // If the current NestedNameSpecifier refers to a class and the
  3608. // current correction candidate is the name of that class, then skip
  3609. // it as it is unlikely a qualified version of the class' constructor
  3610. // is an appropriate correction.
  3611. if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
  3612. nullptr) {
  3613. if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
  3614. continue;
  3615. }
  3616. TypoCorrection TC(QR);
  3617. TC.ClearCorrectionDecls();
  3618. TC.setCorrectionSpecifier(NSI.NameSpecifier);
  3619. TC.setQualifierDistance(NSI.EditDistance);
  3620. TC.setCallbackDistance(0); // Reset the callback distance
  3621. // If the current correction candidate and namespace combination are
  3622. // too far away from the original typo based on the normalized edit
  3623. // distance, then skip performing a qualified name lookup.
  3624. unsigned TmpED = TC.getEditDistance(true);
  3625. if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
  3626. TypoLen / TmpED < 3)
  3627. continue;
  3628. Result.clear();
  3629. Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
  3630. if (!SemaRef.LookupQualifiedName(Result, Ctx))
  3631. continue;
  3632. // Any corrections added below will be validated in subsequent
  3633. // iterations of the main while() loop over the Consumer's contents.
  3634. switch (Result.getResultKind()) {
  3635. case LookupResult::Found:
  3636. case LookupResult::FoundOverloaded: {
  3637. if (SS && SS->isValid()) {
  3638. std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
  3639. std::string OldQualified;
  3640. llvm::raw_string_ostream OldOStream(OldQualified);
  3641. SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
  3642. OldOStream << Typo->getName();
  3643. // If correction candidate would be an identical written qualified
  3644. // identifier, then the existing CXXScopeSpec probably included a
  3645. // typedef that didn't get accounted for properly.
  3646. if (OldOStream.str() == NewQualified)
  3647. break;
  3648. }
  3649. for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
  3650. TRD != TRDEnd; ++TRD) {
  3651. if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
  3652. NSType ? NSType->getAsCXXRecordDecl()
  3653. : nullptr,
  3654. TRD.getPair()) == Sema::AR_accessible)
  3655. TC.addCorrectionDecl(*TRD);
  3656. }
  3657. if (TC.isResolved()) {
  3658. TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
  3659. addCorrection(TC);
  3660. }
  3661. break;
  3662. }
  3663. case LookupResult::NotFound:
  3664. case LookupResult::NotFoundInCurrentInstantiation:
  3665. case LookupResult::Ambiguous:
  3666. case LookupResult::FoundUnresolvedValue:
  3667. break;
  3668. }
  3669. }
  3670. }
  3671. QualifiedResults.clear();
  3672. }
  3673. TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
  3674. ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
  3675. : Context(Context), CurContextChain(buildContextChain(CurContext)) {
  3676. if (NestedNameSpecifier *NNS =
  3677. CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
  3678. llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
  3679. NNS->print(SpecifierOStream, Context.getPrintingPolicy());
  3680. getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
  3681. }
  3682. // Build the list of identifiers that would be used for an absolute
  3683. // (from the global context) NestedNameSpecifier referring to the current
  3684. // context.
  3685. for (DeclContext *C : llvm::reverse(CurContextChain)) {
  3686. if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
  3687. CurContextIdentifiers.push_back(ND->getIdentifier());
  3688. }
  3689. // Add the global context as a NestedNameSpecifier
  3690. SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
  3691. NestedNameSpecifier::GlobalSpecifier(Context), 1};
  3692. DistanceMap[1].push_back(SI);
  3693. }
  3694. auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
  3695. DeclContext *Start) -> DeclContextList {
  3696. assert(Start && "Building a context chain from a null context");
  3697. DeclContextList Chain;
  3698. for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
  3699. DC = DC->getLookupParent()) {
  3700. NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
  3701. if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
  3702. !(ND && ND->isAnonymousNamespace()))
  3703. Chain.push_back(DC->getPrimaryContext());
  3704. }
  3705. return Chain;
  3706. }
  3707. unsigned
  3708. TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
  3709. DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
  3710. unsigned NumSpecifiers = 0;
  3711. for (DeclContext *C : llvm::reverse(DeclChain)) {
  3712. if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
  3713. NNS = NestedNameSpecifier::Create(Context, NNS, ND);
  3714. ++NumSpecifiers;
  3715. } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
  3716. NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
  3717. RD->getTypeForDecl());
  3718. ++NumSpecifiers;
  3719. }
  3720. }
  3721. return NumSpecifiers;
  3722. }
  3723. void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
  3724. DeclContext *Ctx) {
  3725. NestedNameSpecifier *NNS = nullptr;
  3726. unsigned NumSpecifiers = 0;
  3727. DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
  3728. DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
  3729. // Eliminate common elements from the two DeclContext chains.
  3730. for (DeclContext *C : llvm::reverse(CurContextChain)) {
  3731. if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
  3732. break;
  3733. NamespaceDeclChain.pop_back();
  3734. }
  3735. // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
  3736. NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
  3737. // Add an explicit leading '::' specifier if needed.
  3738. if (NamespaceDeclChain.empty()) {
  3739. // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
  3740. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  3741. NumSpecifiers =
  3742. buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
  3743. } else if (NamedDecl *ND =
  3744. dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
  3745. IdentifierInfo *Name = ND->getIdentifier();
  3746. bool SameNameSpecifier = false;
  3747. if (std::find(CurNameSpecifierIdentifiers.begin(),
  3748. CurNameSpecifierIdentifiers.end(),
  3749. Name) != CurNameSpecifierIdentifiers.end()) {
  3750. std::string NewNameSpecifier;
  3751. llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
  3752. SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
  3753. getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
  3754. NNS->print(SpecifierOStream, Context.getPrintingPolicy());
  3755. SpecifierOStream.flush();
  3756. SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
  3757. }
  3758. if (SameNameSpecifier ||
  3759. std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
  3760. Name) != CurContextIdentifiers.end()) {
  3761. // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
  3762. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  3763. NumSpecifiers =
  3764. buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
  3765. }
  3766. }
  3767. // If the built NestedNameSpecifier would be replacing an existing
  3768. // NestedNameSpecifier, use the number of component identifiers that
  3769. // would need to be changed as the edit distance instead of the number
  3770. // of components in the built NestedNameSpecifier.
  3771. if (NNS && !CurNameSpecifierIdentifiers.empty()) {
  3772. SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
  3773. getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
  3774. NumSpecifiers = llvm::ComputeEditDistance(
  3775. llvm::makeArrayRef(CurNameSpecifierIdentifiers),
  3776. llvm::makeArrayRef(NewNameSpecifierIdentifiers));
  3777. }
  3778. SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
  3779. DistanceMap[NumSpecifiers].push_back(SI);
  3780. }
  3781. /// Perform name lookup for a possible result for typo correction.
  3782. static void LookupPotentialTypoResult(Sema &SemaRef,
  3783. LookupResult &Res,
  3784. IdentifierInfo *Name,
  3785. Scope *S, CXXScopeSpec *SS,
  3786. DeclContext *MemberContext,
  3787. bool EnteringContext,
  3788. bool isObjCIvarLookup,
  3789. bool FindHidden) {
  3790. Res.suppressDiagnostics();
  3791. Res.clear();
  3792. Res.setLookupName(Name);
  3793. Res.setAllowHidden(FindHidden);
  3794. if (MemberContext) {
  3795. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
  3796. if (isObjCIvarLookup) {
  3797. if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
  3798. Res.addDecl(Ivar);
  3799. Res.resolveKind();
  3800. return;
  3801. }
  3802. }
  3803. if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
  3804. Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  3805. Res.addDecl(Prop);
  3806. Res.resolveKind();
  3807. return;
  3808. }
  3809. }
  3810. SemaRef.LookupQualifiedName(Res, MemberContext);
  3811. return;
  3812. }
  3813. SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
  3814. EnteringContext);
  3815. // Fake ivar lookup; this should really be part of
  3816. // LookupParsedName.
  3817. if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
  3818. if (Method->isInstanceMethod() && Method->getClassInterface() &&
  3819. (Res.empty() ||
  3820. (Res.isSingleResult() &&
  3821. Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
  3822. if (ObjCIvarDecl *IV
  3823. = Method->getClassInterface()->lookupInstanceVariable(Name)) {
  3824. Res.addDecl(IV);
  3825. Res.resolveKind();
  3826. }
  3827. }
  3828. }
  3829. }
  3830. /// Add keywords to the consumer as possible typo corrections.
  3831. static void AddKeywordsToConsumer(Sema &SemaRef,
  3832. TypoCorrectionConsumer &Consumer,
  3833. Scope *S, CorrectionCandidateCallback &CCC,
  3834. bool AfterNestedNameSpecifier) {
  3835. if (AfterNestedNameSpecifier) {
  3836. // For 'X::', we know exactly which keywords can appear next.
  3837. Consumer.addKeywordResult("template");
  3838. if (CCC.WantExpressionKeywords)
  3839. Consumer.addKeywordResult("operator");
  3840. return;
  3841. }
  3842. if (CCC.WantObjCSuper)
  3843. Consumer.addKeywordResult("super");
  3844. if (CCC.WantTypeSpecifiers) {
  3845. // Add type-specifier keywords to the set of results.
  3846. static const char *const CTypeSpecs[] = {
  3847. "char", "const", "double", "enum", "float", "int", "long", "short",
  3848. "signed", "struct", "union", "unsigned", "void", "volatile",
  3849. "_Complex", "_Imaginary",
  3850. // storage-specifiers as well
  3851. "extern", "inline", "static", "typedef"
  3852. };
  3853. const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
  3854. for (unsigned I = 0; I != NumCTypeSpecs; ++I)
  3855. Consumer.addKeywordResult(CTypeSpecs[I]);
  3856. if (SemaRef.getLangOpts().C99)
  3857. Consumer.addKeywordResult("restrict");
  3858. if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
  3859. Consumer.addKeywordResult("bool");
  3860. else if (SemaRef.getLangOpts().C99)
  3861. Consumer.addKeywordResult("_Bool");
  3862. if (SemaRef.getLangOpts().CPlusPlus) {
  3863. Consumer.addKeywordResult("class");
  3864. Consumer.addKeywordResult("typename");
  3865. Consumer.addKeywordResult("wchar_t");
  3866. if (SemaRef.getLangOpts().CPlusPlus11) {
  3867. Consumer.addKeywordResult("char16_t");
  3868. Consumer.addKeywordResult("char32_t");
  3869. Consumer.addKeywordResult("constexpr");
  3870. Consumer.addKeywordResult("decltype");
  3871. Consumer.addKeywordResult("thread_local");
  3872. }
  3873. }
  3874. if (SemaRef.getLangOpts().GNUKeywords)
  3875. Consumer.addKeywordResult("typeof");
  3876. } else if (CCC.WantFunctionLikeCasts) {
  3877. static const char *const CastableTypeSpecs[] = {
  3878. "char", "double", "float", "int", "long", "short",
  3879. "signed", "unsigned", "void"
  3880. };
  3881. for (auto *kw : CastableTypeSpecs)
  3882. Consumer.addKeywordResult(kw);
  3883. }
  3884. if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
  3885. Consumer.addKeywordResult("const_cast");
  3886. Consumer.addKeywordResult("dynamic_cast");
  3887. Consumer.addKeywordResult("reinterpret_cast");
  3888. Consumer.addKeywordResult("static_cast");
  3889. }
  3890. if (CCC.WantExpressionKeywords) {
  3891. Consumer.addKeywordResult("sizeof");
  3892. if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
  3893. Consumer.addKeywordResult("false");
  3894. Consumer.addKeywordResult("true");
  3895. }
  3896. if (SemaRef.getLangOpts().CPlusPlus) {
  3897. static const char *const CXXExprs[] = {
  3898. "delete", "new", "operator", "throw", "typeid"
  3899. };
  3900. const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
  3901. for (unsigned I = 0; I != NumCXXExprs; ++I)
  3902. Consumer.addKeywordResult(CXXExprs[I]);
  3903. if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
  3904. cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
  3905. Consumer.addKeywordResult("this");
  3906. if (SemaRef.getLangOpts().CPlusPlus11) {
  3907. Consumer.addKeywordResult("alignof");
  3908. Consumer.addKeywordResult("nullptr");
  3909. }
  3910. }
  3911. if (SemaRef.getLangOpts().C11) {
  3912. // FIXME: We should not suggest _Alignof if the alignof macro
  3913. // is present.
  3914. Consumer.addKeywordResult("_Alignof");
  3915. }
  3916. }
  3917. if (CCC.WantRemainingKeywords) {
  3918. if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
  3919. // Statements.
  3920. static const char *const CStmts[] = {
  3921. "do", "else", "for", "goto", "if", "return", "switch", "while" };
  3922. const unsigned NumCStmts = llvm::array_lengthof(CStmts);
  3923. for (unsigned I = 0; I != NumCStmts; ++I)
  3924. Consumer.addKeywordResult(CStmts[I]);
  3925. if (SemaRef.getLangOpts().CPlusPlus) {
  3926. Consumer.addKeywordResult("catch");
  3927. Consumer.addKeywordResult("try");
  3928. }
  3929. if (S && S->getBreakParent())
  3930. Consumer.addKeywordResult("break");
  3931. if (S && S->getContinueParent())
  3932. Consumer.addKeywordResult("continue");
  3933. if (SemaRef.getCurFunction() &&
  3934. !SemaRef.getCurFunction()->SwitchStack.empty()) {
  3935. Consumer.addKeywordResult("case");
  3936. Consumer.addKeywordResult("default");
  3937. }
  3938. } else {
  3939. if (SemaRef.getLangOpts().CPlusPlus) {
  3940. Consumer.addKeywordResult("namespace");
  3941. Consumer.addKeywordResult("template");
  3942. }
  3943. if (S && S->isClassScope()) {
  3944. Consumer.addKeywordResult("explicit");
  3945. Consumer.addKeywordResult("friend");
  3946. Consumer.addKeywordResult("mutable");
  3947. Consumer.addKeywordResult("private");
  3948. Consumer.addKeywordResult("protected");
  3949. Consumer.addKeywordResult("public");
  3950. Consumer.addKeywordResult("virtual");
  3951. }
  3952. }
  3953. if (SemaRef.getLangOpts().CPlusPlus) {
  3954. Consumer.addKeywordResult("using");
  3955. if (SemaRef.getLangOpts().CPlusPlus11)
  3956. Consumer.addKeywordResult("static_assert");
  3957. }
  3958. }
  3959. }
  3960. std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
  3961. const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
  3962. Scope *S, CXXScopeSpec *SS,
  3963. std::unique_ptr<CorrectionCandidateCallback> CCC,
  3964. DeclContext *MemberContext, bool EnteringContext,
  3965. const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
  3966. if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
  3967. DisableTypoCorrection)
  3968. return nullptr;
  3969. // In Microsoft mode, don't perform typo correction in a template member
  3970. // function dependent context because it interferes with the "lookup into
  3971. // dependent bases of class templates" feature.
  3972. if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
  3973. isa<CXXMethodDecl>(CurContext))
  3974. return nullptr;
  3975. // We only attempt to correct typos for identifiers.
  3976. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  3977. if (!Typo)
  3978. return nullptr;
  3979. // If the scope specifier itself was invalid, don't try to correct
  3980. // typos.
  3981. if (SS && SS->isInvalid())
  3982. return nullptr;
  3983. // Never try to correct typos during any kind of code synthesis.
  3984. if (!CodeSynthesisContexts.empty())
  3985. return nullptr;
  3986. // Don't try to correct 'super'.
  3987. if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
  3988. return nullptr;
  3989. // Abort if typo correction already failed for this specific typo.
  3990. IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
  3991. if (locs != TypoCorrectionFailures.end() &&
  3992. locs->second.count(TypoName.getLoc()))
  3993. return nullptr;
  3994. // Don't try to correct the identifier "vector" when in AltiVec mode.
  3995. // TODO: Figure out why typo correction misbehaves in this case, fix it, and
  3996. // remove this workaround.
  3997. if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
  3998. return nullptr;
  3999. // Provide a stop gap for files that are just seriously broken. Trying
  4000. // to correct all typos can turn into a HUGE performance penalty, causing
  4001. // some files to take minutes to get rejected by the parser.
  4002. unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
  4003. if (Limit && TyposCorrected >= Limit)
  4004. return nullptr;
  4005. ++TyposCorrected;
  4006. // If we're handling a missing symbol error, using modules, and the
  4007. // special search all modules option is used, look for a missing import.
  4008. if (ErrorRecovery && getLangOpts().Modules &&
  4009. getLangOpts().ModulesSearchAll) {
  4010. // The following has the side effect of loading the missing module.
  4011. getModuleLoader().lookupMissingImports(Typo->getName(),
  4012. TypoName.getBeginLoc());
  4013. }
  4014. CorrectionCandidateCallback &CCCRef = *CCC;
  4015. auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
  4016. *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
  4017. EnteringContext);
  4018. // Perform name lookup to find visible, similarly-named entities.
  4019. bool IsUnqualifiedLookup = false;
  4020. DeclContext *QualifiedDC = MemberContext;
  4021. if (MemberContext) {
  4022. LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
  4023. // Look in qualified interfaces.
  4024. if (OPT) {
  4025. for (auto *I : OPT->quals())
  4026. LookupVisibleDecls(I, LookupKind, *Consumer);
  4027. }
  4028. } else if (SS && SS->isSet()) {
  4029. QualifiedDC = computeDeclContext(*SS, EnteringContext);
  4030. if (!QualifiedDC)
  4031. return nullptr;
  4032. LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
  4033. } else {
  4034. IsUnqualifiedLookup = true;
  4035. }
  4036. // Determine whether we are going to search in the various namespaces for
  4037. // corrections.
  4038. bool SearchNamespaces
  4039. = getLangOpts().CPlusPlus &&
  4040. (IsUnqualifiedLookup || (SS && SS->isSet()));
  4041. if (IsUnqualifiedLookup || SearchNamespaces) {
  4042. // For unqualified lookup, look through all of the names that we have
  4043. // seen in this translation unit.
  4044. // FIXME: Re-add the ability to skip very unlikely potential corrections.
  4045. for (const auto &I : Context.Idents)
  4046. Consumer->FoundName(I.getKey());
  4047. // Walk through identifiers in external identifier sources.
  4048. // FIXME: Re-add the ability to skip very unlikely potential corrections.
  4049. if (IdentifierInfoLookup *External
  4050. = Context.Idents.getExternalIdentifierLookup()) {
  4051. std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
  4052. do {
  4053. StringRef Name = Iter->Next();
  4054. if (Name.empty())
  4055. break;
  4056. Consumer->FoundName(Name);
  4057. } while (true);
  4058. }
  4059. }
  4060. AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
  4061. // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
  4062. // to search those namespaces.
  4063. if (SearchNamespaces) {
  4064. // Load any externally-known namespaces.
  4065. if (ExternalSource && !LoadedExternalKnownNamespaces) {
  4066. SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
  4067. LoadedExternalKnownNamespaces = true;
  4068. ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
  4069. for (auto *N : ExternalKnownNamespaces)
  4070. KnownNamespaces[N] = true;
  4071. }
  4072. Consumer->addNamespaces(KnownNamespaces);
  4073. }
  4074. return Consumer;
  4075. }
  4076. /// Try to "correct" a typo in the source code by finding
  4077. /// visible declarations whose names are similar to the name that was
  4078. /// present in the source code.
  4079. ///
  4080. /// \param TypoName the \c DeclarationNameInfo structure that contains
  4081. /// the name that was present in the source code along with its location.
  4082. ///
  4083. /// \param LookupKind the name-lookup criteria used to search for the name.
  4084. ///
  4085. /// \param S the scope in which name lookup occurs.
  4086. ///
  4087. /// \param SS the nested-name-specifier that precedes the name we're
  4088. /// looking for, if present.
  4089. ///
  4090. /// \param CCC A CorrectionCandidateCallback object that provides further
  4091. /// validation of typo correction candidates. It also provides flags for
  4092. /// determining the set of keywords permitted.
  4093. ///
  4094. /// \param MemberContext if non-NULL, the context in which to look for
  4095. /// a member access expression.
  4096. ///
  4097. /// \param EnteringContext whether we're entering the context described by
  4098. /// the nested-name-specifier SS.
  4099. ///
  4100. /// \param OPT when non-NULL, the search for visible declarations will
  4101. /// also walk the protocols in the qualified interfaces of \p OPT.
  4102. ///
  4103. /// \returns a \c TypoCorrection containing the corrected name if the typo
  4104. /// along with information such as the \c NamedDecl where the corrected name
  4105. /// was declared, and any additional \c NestedNameSpecifier needed to access
  4106. /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
  4107. TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
  4108. Sema::LookupNameKind LookupKind,
  4109. Scope *S, CXXScopeSpec *SS,
  4110. std::unique_ptr<CorrectionCandidateCallback> CCC,
  4111. CorrectTypoKind Mode,
  4112. DeclContext *MemberContext,
  4113. bool EnteringContext,
  4114. const ObjCObjectPointerType *OPT,
  4115. bool RecordFailure) {
  4116. assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
  4117. // Always let the ExternalSource have the first chance at correction, even
  4118. // if we would otherwise have given up.
  4119. if (ExternalSource) {
  4120. if (TypoCorrection Correction = ExternalSource->CorrectTypo(
  4121. TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
  4122. return Correction;
  4123. }
  4124. // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
  4125. // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
  4126. // some instances of CTC_Unknown, while WantRemainingKeywords is true
  4127. // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
  4128. bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
  4129. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  4130. auto Consumer = makeTypoCorrectionConsumer(
  4131. TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
  4132. EnteringContext, OPT, Mode == CTK_ErrorRecovery);
  4133. if (!Consumer)
  4134. return TypoCorrection();
  4135. // If we haven't found anything, we're done.
  4136. if (Consumer->empty())
  4137. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4138. // Make sure the best edit distance (prior to adding any namespace qualifiers)
  4139. // is not more that about a third of the length of the typo's identifier.
  4140. unsigned ED = Consumer->getBestEditDistance(true);
  4141. unsigned TypoLen = Typo->getName().size();
  4142. if (ED > 0 && TypoLen / ED < 3)
  4143. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4144. TypoCorrection BestTC = Consumer->getNextCorrection();
  4145. TypoCorrection SecondBestTC = Consumer->getNextCorrection();
  4146. if (!BestTC)
  4147. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4148. ED = BestTC.getEditDistance();
  4149. if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
  4150. // If this was an unqualified lookup and we believe the callback
  4151. // object wouldn't have filtered out possible corrections, note
  4152. // that no correction was found.
  4153. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4154. }
  4155. // If only a single name remains, return that result.
  4156. if (!SecondBestTC ||
  4157. SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
  4158. const TypoCorrection &Result = BestTC;
  4159. // Don't correct to a keyword that's the same as the typo; the keyword
  4160. // wasn't actually in scope.
  4161. if (ED == 0 && Result.isKeyword())
  4162. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4163. TypoCorrection TC = Result;
  4164. TC.setCorrectionRange(SS, TypoName);
  4165. checkCorrectionVisibility(*this, TC);
  4166. return TC;
  4167. } else if (SecondBestTC && ObjCMessageReceiver) {
  4168. // Prefer 'super' when we're completing in a message-receiver
  4169. // context.
  4170. if (BestTC.getCorrection().getAsString() != "super") {
  4171. if (SecondBestTC.getCorrection().getAsString() == "super")
  4172. BestTC = SecondBestTC;
  4173. else if ((*Consumer)["super"].front().isKeyword())
  4174. BestTC = (*Consumer)["super"].front();
  4175. }
  4176. // Don't correct to a keyword that's the same as the typo; the keyword
  4177. // wasn't actually in scope.
  4178. if (BestTC.getEditDistance() == 0 ||
  4179. BestTC.getCorrection().getAsString() != "super")
  4180. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4181. BestTC.setCorrectionRange(SS, TypoName);
  4182. return BestTC;
  4183. }
  4184. // Record the failure's location if needed and return an empty correction. If
  4185. // this was an unqualified lookup and we believe the callback object did not
  4186. // filter out possible corrections, also cache the failure for the typo.
  4187. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
  4188. }
  4189. /// Try to "correct" a typo in the source code by finding
  4190. /// visible declarations whose names are similar to the name that was
  4191. /// present in the source code.
  4192. ///
  4193. /// \param TypoName the \c DeclarationNameInfo structure that contains
  4194. /// the name that was present in the source code along with its location.
  4195. ///
  4196. /// \param LookupKind the name-lookup criteria used to search for the name.
  4197. ///
  4198. /// \param S the scope in which name lookup occurs.
  4199. ///
  4200. /// \param SS the nested-name-specifier that precedes the name we're
  4201. /// looking for, if present.
  4202. ///
  4203. /// \param CCC A CorrectionCandidateCallback object that provides further
  4204. /// validation of typo correction candidates. It also provides flags for
  4205. /// determining the set of keywords permitted.
  4206. ///
  4207. /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
  4208. /// diagnostics when the actual typo correction is attempted.
  4209. ///
  4210. /// \param TRC A TypoRecoveryCallback functor that will be used to build an
  4211. /// Expr from a typo correction candidate.
  4212. ///
  4213. /// \param MemberContext if non-NULL, the context in which to look for
  4214. /// a member access expression.
  4215. ///
  4216. /// \param EnteringContext whether we're entering the context described by
  4217. /// the nested-name-specifier SS.
  4218. ///
  4219. /// \param OPT when non-NULL, the search for visible declarations will
  4220. /// also walk the protocols in the qualified interfaces of \p OPT.
  4221. ///
  4222. /// \returns a new \c TypoExpr that will later be replaced in the AST with an
  4223. /// Expr representing the result of performing typo correction, or nullptr if
  4224. /// typo correction is not possible. If nullptr is returned, no diagnostics will
  4225. /// be emitted and it is the responsibility of the caller to emit any that are
  4226. /// needed.
  4227. TypoExpr *Sema::CorrectTypoDelayed(
  4228. const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
  4229. Scope *S, CXXScopeSpec *SS,
  4230. std::unique_ptr<CorrectionCandidateCallback> CCC,
  4231. TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
  4232. DeclContext *MemberContext, bool EnteringContext,
  4233. const ObjCObjectPointerType *OPT) {
  4234. assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
  4235. auto Consumer = makeTypoCorrectionConsumer(
  4236. TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
  4237. EnteringContext, OPT, Mode == CTK_ErrorRecovery);
  4238. // Give the external sema source a chance to correct the typo.
  4239. TypoCorrection ExternalTypo;
  4240. if (ExternalSource && Consumer) {
  4241. ExternalTypo = ExternalSource->CorrectTypo(
  4242. TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
  4243. MemberContext, EnteringContext, OPT);
  4244. if (ExternalTypo)
  4245. Consumer->addCorrection(ExternalTypo);
  4246. }
  4247. if (!Consumer || Consumer->empty())
  4248. return nullptr;
  4249. // Make sure the best edit distance (prior to adding any namespace qualifiers)
  4250. // is not more that about a third of the length of the typo's identifier.
  4251. unsigned ED = Consumer->getBestEditDistance(true);
  4252. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  4253. if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
  4254. return nullptr;
  4255. ExprEvalContexts.back().NumTypos++;
  4256. return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
  4257. }
  4258. void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
  4259. if (!CDecl) return;
  4260. if (isKeyword())
  4261. CorrectionDecls.clear();
  4262. CorrectionDecls.push_back(CDecl);
  4263. if (!CorrectionName)
  4264. CorrectionName = CDecl->getDeclName();
  4265. }
  4266. std::string TypoCorrection::getAsString(const LangOptions &LO) const {
  4267. if (CorrectionNameSpec) {
  4268. std::string tmpBuffer;
  4269. llvm::raw_string_ostream PrefixOStream(tmpBuffer);
  4270. CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
  4271. PrefixOStream << CorrectionName;
  4272. return PrefixOStream.str();
  4273. }
  4274. return CorrectionName.getAsString();
  4275. }
  4276. bool CorrectionCandidateCallback::ValidateCandidate(
  4277. const TypoCorrection &candidate) {
  4278. if (!candidate.isResolved())
  4279. return true;
  4280. if (candidate.isKeyword())
  4281. return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
  4282. WantRemainingKeywords || WantObjCSuper;
  4283. bool HasNonType = false;
  4284. bool HasStaticMethod = false;
  4285. bool HasNonStaticMethod = false;
  4286. for (Decl *D : candidate) {
  4287. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
  4288. D = FTD->getTemplatedDecl();
  4289. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  4290. if (Method->isStatic())
  4291. HasStaticMethod = true;
  4292. else
  4293. HasNonStaticMethod = true;
  4294. }
  4295. if (!isa<TypeDecl>(D))
  4296. HasNonType = true;
  4297. }
  4298. if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
  4299. !candidate.getCorrectionSpecifier())
  4300. return false;
  4301. return WantTypeSpecifiers || HasNonType;
  4302. }
  4303. FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
  4304. bool HasExplicitTemplateArgs,
  4305. MemberExpr *ME)
  4306. : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
  4307. CurContext(SemaRef.CurContext), MemberFn(ME) {
  4308. WantTypeSpecifiers = false;
  4309. WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
  4310. WantRemainingKeywords = false;
  4311. }
  4312. bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
  4313. if (!candidate.getCorrectionDecl())
  4314. return candidate.isKeyword();
  4315. for (auto *C : candidate) {
  4316. FunctionDecl *FD = nullptr;
  4317. NamedDecl *ND = C->getUnderlyingDecl();
  4318. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  4319. FD = FTD->getTemplatedDecl();
  4320. if (!HasExplicitTemplateArgs && !FD) {
  4321. if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
  4322. // If the Decl is neither a function nor a template function,
  4323. // determine if it is a pointer or reference to a function. If so,
  4324. // check against the number of arguments expected for the pointee.
  4325. QualType ValType = cast<ValueDecl>(ND)->getType();
  4326. if (ValType.isNull())
  4327. continue;
  4328. if (ValType->isAnyPointerType() || ValType->isReferenceType())
  4329. ValType = ValType->getPointeeType();
  4330. if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
  4331. if (FPT->getNumParams() == NumArgs)
  4332. return true;
  4333. }
  4334. }
  4335. // Skip the current candidate if it is not a FunctionDecl or does not accept
  4336. // the current number of arguments.
  4337. if (!FD || !(FD->getNumParams() >= NumArgs &&
  4338. FD->getMinRequiredArguments() <= NumArgs))
  4339. continue;
  4340. // If the current candidate is a non-static C++ method, skip the candidate
  4341. // unless the method being corrected--or the current DeclContext, if the
  4342. // function being corrected is not a method--is a method in the same class
  4343. // or a descendent class of the candidate's parent class.
  4344. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  4345. if (MemberFn || !MD->isStatic()) {
  4346. CXXMethodDecl *CurMD =
  4347. MemberFn
  4348. ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
  4349. : dyn_cast_or_null<CXXMethodDecl>(CurContext);
  4350. CXXRecordDecl *CurRD =
  4351. CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
  4352. CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
  4353. if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
  4354. continue;
  4355. }
  4356. }
  4357. return true;
  4358. }
  4359. return false;
  4360. }
  4361. void Sema::diagnoseTypo(const TypoCorrection &Correction,
  4362. const PartialDiagnostic &TypoDiag,
  4363. bool ErrorRecovery) {
  4364. diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
  4365. ErrorRecovery);
  4366. }
  4367. /// Find which declaration we should import to provide the definition of
  4368. /// the given declaration.
  4369. static NamedDecl *getDefinitionToImport(NamedDecl *D) {
  4370. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  4371. return VD->getDefinition();
  4372. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  4373. return FD->getDefinition();
  4374. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  4375. return TD->getDefinition();
  4376. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
  4377. return ID->getDefinition();
  4378. if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
  4379. return PD->getDefinition();
  4380. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  4381. return getDefinitionToImport(TD->getTemplatedDecl());
  4382. return nullptr;
  4383. }
  4384. void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
  4385. MissingImportKind MIK, bool Recover) {
  4386. // Suggest importing a module providing the definition of this entity, if
  4387. // possible.
  4388. NamedDecl *Def = getDefinitionToImport(Decl);
  4389. if (!Def)
  4390. Def = Decl;
  4391. Module *Owner = getOwningModule(Def);
  4392. assert(Owner && "definition of hidden declaration is not in a module");
  4393. llvm::SmallVector<Module*, 8> OwningModules;
  4394. OwningModules.push_back(Owner);
  4395. auto Merged = Context.getModulesWithMergedDefinition(Def);
  4396. OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
  4397. diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
  4398. Recover);
  4399. }
  4400. /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
  4401. /// suggesting the addition of a #include of the specified file.
  4402. static std::string getIncludeStringForHeader(Preprocessor &PP,
  4403. const FileEntry *E) {
  4404. bool IsSystem;
  4405. auto Path =
  4406. PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
  4407. return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
  4408. }
  4409. void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
  4410. SourceLocation DeclLoc,
  4411. ArrayRef<Module *> Modules,
  4412. MissingImportKind MIK, bool Recover) {
  4413. assert(!Modules.empty());
  4414. // Weed out duplicates from module list.
  4415. llvm::SmallVector<Module*, 8> UniqueModules;
  4416. llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
  4417. for (auto *M : Modules)
  4418. if (UniqueModuleSet.insert(M).second)
  4419. UniqueModules.push_back(M);
  4420. Modules = UniqueModules;
  4421. if (Modules.size() > 1) {
  4422. std::string ModuleList;
  4423. unsigned N = 0;
  4424. for (Module *M : Modules) {
  4425. ModuleList += "\n ";
  4426. if (++N == 5 && N != Modules.size()) {
  4427. ModuleList += "[...]";
  4428. break;
  4429. }
  4430. ModuleList += M->getFullModuleName();
  4431. }
  4432. Diag(UseLoc, diag::err_module_unimported_use_multiple)
  4433. << (int)MIK << Decl << ModuleList;
  4434. } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
  4435. UseLoc, Modules[0], DeclLoc)) {
  4436. // The right way to make the declaration visible is to include a header;
  4437. // suggest doing so.
  4438. //
  4439. // FIXME: Find a smart place to suggest inserting a #include, and add
  4440. // a FixItHint there.
  4441. Diag(UseLoc, diag::err_module_unimported_use_header)
  4442. << (int)MIK << Decl << Modules[0]->getFullModuleName()
  4443. << getIncludeStringForHeader(PP, E);
  4444. } else {
  4445. // FIXME: Add a FixItHint that imports the corresponding module.
  4446. Diag(UseLoc, diag::err_module_unimported_use)
  4447. << (int)MIK << Decl << Modules[0]->getFullModuleName();
  4448. }
  4449. unsigned DiagID;
  4450. switch (MIK) {
  4451. case MissingImportKind::Declaration:
  4452. DiagID = diag::note_previous_declaration;
  4453. break;
  4454. case MissingImportKind::Definition:
  4455. DiagID = diag::note_previous_definition;
  4456. break;
  4457. case MissingImportKind::DefaultArgument:
  4458. DiagID = diag::note_default_argument_declared_here;
  4459. break;
  4460. case MissingImportKind::ExplicitSpecialization:
  4461. DiagID = diag::note_explicit_specialization_declared_here;
  4462. break;
  4463. case MissingImportKind::PartialSpecialization:
  4464. DiagID = diag::note_partial_specialization_declared_here;
  4465. break;
  4466. }
  4467. Diag(DeclLoc, DiagID);
  4468. // Try to recover by implicitly importing this module.
  4469. if (Recover)
  4470. createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
  4471. }
  4472. /// Diagnose a successfully-corrected typo. Separated from the correction
  4473. /// itself to allow external validation of the result, etc.
  4474. ///
  4475. /// \param Correction The result of performing typo correction.
  4476. /// \param TypoDiag The diagnostic to produce. This will have the corrected
  4477. /// string added to it (and usually also a fixit).
  4478. /// \param PrevNote A note to use when indicating the location of the entity to
  4479. /// which we are correcting. Will have the correction string added to it.
  4480. /// \param ErrorRecovery If \c true (the default), the caller is going to
  4481. /// recover from the typo as if the corrected string had been typed.
  4482. /// In this case, \c PDiag must be an error, and we will attach a fixit
  4483. /// to it.
  4484. void Sema::diagnoseTypo(const TypoCorrection &Correction,
  4485. const PartialDiagnostic &TypoDiag,
  4486. const PartialDiagnostic &PrevNote,
  4487. bool ErrorRecovery) {
  4488. std::string CorrectedStr = Correction.getAsString(getLangOpts());
  4489. std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
  4490. FixItHint FixTypo = FixItHint::CreateReplacement(
  4491. Correction.getCorrectionRange(), CorrectedStr);
  4492. // Maybe we're just missing a module import.
  4493. if (Correction.requiresImport()) {
  4494. NamedDecl *Decl = Correction.getFoundDecl();
  4495. assert(Decl && "import required but no declaration to import");
  4496. diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
  4497. MissingImportKind::Declaration, ErrorRecovery);
  4498. return;
  4499. }
  4500. Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
  4501. << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
  4502. NamedDecl *ChosenDecl =
  4503. Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
  4504. if (PrevNote.getDiagID() && ChosenDecl)
  4505. Diag(ChosenDecl->getLocation(), PrevNote)
  4506. << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
  4507. // Add any extra diagnostics.
  4508. for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
  4509. Diag(Correction.getCorrectionRange().getBegin(), PD);
  4510. }
  4511. TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
  4512. TypoDiagnosticGenerator TDG,
  4513. TypoRecoveryCallback TRC) {
  4514. assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
  4515. auto TE = new (Context) TypoExpr(Context.DependentTy);
  4516. auto &State = DelayedTypos[TE];
  4517. State.Consumer = std::move(TCC);
  4518. State.DiagHandler = std::move(TDG);
  4519. State.RecoveryHandler = std::move(TRC);
  4520. return TE;
  4521. }
  4522. const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
  4523. auto Entry = DelayedTypos.find(TE);
  4524. assert(Entry != DelayedTypos.end() &&
  4525. "Failed to get the state for a TypoExpr!");
  4526. return Entry->second;
  4527. }
  4528. void Sema::clearDelayedTypo(TypoExpr *TE) {
  4529. DelayedTypos.erase(TE);
  4530. }
  4531. void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
  4532. DeclarationNameInfo Name(II, IILoc);
  4533. LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
  4534. R.suppressDiagnostics();
  4535. R.setHideTags(false);
  4536. LookupName(R, S);
  4537. R.dump();
  4538. }