SemaLookup.cpp 207 KB

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