SemaLookup.cpp 201 KB

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