CIndex.cpp 316 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523
  1. //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
  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 the main API hooks in the Clang-C Source Indexing
  10. // library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CIndexDiagnostic.h"
  14. #include "CIndexer.h"
  15. #include "CLog.h"
  16. #include "CXCursor.h"
  17. #include "CXSourceLocation.h"
  18. #include "CXString.h"
  19. #include "CXTranslationUnit.h"
  20. #include "CXType.h"
  21. #include "CursorVisitor.h"
  22. #include "clang-c/FatalErrorHandler.h"
  23. #include "clang/AST/Attr.h"
  24. #include "clang/AST/DeclObjCCommon.h"
  25. #include "clang/AST/Mangle.h"
  26. #include "clang/AST/OpenMPClause.h"
  27. #include "clang/AST/StmtVisitor.h"
  28. #include "clang/Basic/Diagnostic.h"
  29. #include "clang/Basic/DiagnosticCategories.h"
  30. #include "clang/Basic/DiagnosticIDs.h"
  31. #include "clang/Basic/Stack.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "clang/Basic/Version.h"
  34. #include "clang/Frontend/ASTUnit.h"
  35. #include "clang/Frontend/CompilerInstance.h"
  36. #include "clang/Index/CommentToXML.h"
  37. #include "clang/Lex/HeaderSearch.h"
  38. #include "clang/Lex/Lexer.h"
  39. #include "clang/Lex/PreprocessingRecord.h"
  40. #include "clang/Lex/Preprocessor.h"
  41. #include "llvm/ADT/STLExtras.h"
  42. #include "llvm/ADT/StringSwitch.h"
  43. #include "llvm/Config/llvm-config.h"
  44. #include "llvm/Support/Compiler.h"
  45. #include "llvm/Support/CrashRecoveryContext.h"
  46. #include "llvm/Support/Format.h"
  47. #include "llvm/Support/ManagedStatic.h"
  48. #include "llvm/Support/MemoryBuffer.h"
  49. #include "llvm/Support/Program.h"
  50. #include "llvm/Support/SaveAndRestore.h"
  51. #include "llvm/Support/Signals.h"
  52. #include "llvm/Support/TargetSelect.h"
  53. #include "llvm/Support/Threading.h"
  54. #include "llvm/Support/Timer.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include "llvm/Support/thread.h"
  57. #include <mutex>
  58. #include <optional>
  59. #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
  60. #define USE_DARWIN_THREADS
  61. #endif
  62. #ifdef USE_DARWIN_THREADS
  63. #include <pthread.h>
  64. #endif
  65. using namespace clang;
  66. using namespace clang::cxcursor;
  67. using namespace clang::cxtu;
  68. using namespace clang::cxindex;
  69. CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
  70. std::unique_ptr<ASTUnit> AU) {
  71. if (!AU)
  72. return nullptr;
  73. assert(CIdx);
  74. CXTranslationUnit D = new CXTranslationUnitImpl();
  75. D->CIdx = CIdx;
  76. D->TheASTUnit = AU.release();
  77. D->StringPool = new cxstring::CXStringPool();
  78. D->Diagnostics = nullptr;
  79. D->OverridenCursorsPool = createOverridenCXCursorsPool();
  80. D->CommentToXML = nullptr;
  81. D->ParsingOptions = 0;
  82. D->Arguments = {};
  83. return D;
  84. }
  85. bool cxtu::isASTReadError(ASTUnit *AU) {
  86. for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
  87. DEnd = AU->stored_diag_end();
  88. D != DEnd; ++D) {
  89. if (D->getLevel() >= DiagnosticsEngine::Error &&
  90. DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
  91. diag::DiagCat_AST_Deserialization_Issue)
  92. return true;
  93. }
  94. return false;
  95. }
  96. cxtu::CXTUOwner::~CXTUOwner() {
  97. if (TU)
  98. clang_disposeTranslationUnit(TU);
  99. }
  100. /// Compare two source ranges to determine their relative position in
  101. /// the translation unit.
  102. static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1,
  103. SourceRange R2) {
  104. assert(R1.isValid() && "First range is invalid?");
  105. assert(R2.isValid() && "Second range is invalid?");
  106. if (R1.getEnd() != R2.getBegin() &&
  107. SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
  108. return RangeBefore;
  109. if (R2.getEnd() != R1.getBegin() &&
  110. SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
  111. return RangeAfter;
  112. return RangeOverlap;
  113. }
  114. /// Determine if a source location falls within, before, or after a
  115. /// a given source range.
  116. static RangeComparisonResult LocationCompare(SourceManager &SM,
  117. SourceLocation L, SourceRange R) {
  118. assert(R.isValid() && "First range is invalid?");
  119. assert(L.isValid() && "Second range is invalid?");
  120. if (L == R.getBegin() || L == R.getEnd())
  121. return RangeOverlap;
  122. if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
  123. return RangeBefore;
  124. if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
  125. return RangeAfter;
  126. return RangeOverlap;
  127. }
  128. /// Translate a Clang source range into a CIndex source range.
  129. ///
  130. /// Clang internally represents ranges where the end location points to the
  131. /// start of the token at the end. However, for external clients it is more
  132. /// useful to have a CXSourceRange be a proper half-open interval. This routine
  133. /// does the appropriate translation.
  134. CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
  135. const LangOptions &LangOpts,
  136. const CharSourceRange &R) {
  137. // We want the last character in this location, so we will adjust the
  138. // location accordingly.
  139. SourceLocation EndLoc = R.getEnd();
  140. bool IsTokenRange = R.isTokenRange();
  141. if (EndLoc.isValid() && EndLoc.isMacroID() &&
  142. !SM.isMacroArgExpansion(EndLoc)) {
  143. CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
  144. EndLoc = Expansion.getEnd();
  145. IsTokenRange = Expansion.isTokenRange();
  146. }
  147. if (IsTokenRange && EndLoc.isValid()) {
  148. unsigned Length =
  149. Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts);
  150. EndLoc = EndLoc.getLocWithOffset(Length);
  151. }
  152. CXSourceRange Result = {
  153. {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()};
  154. return Result;
  155. }
  156. CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) {
  157. return CharSourceRange::getCharRange(
  158. SourceLocation::getFromRawEncoding(R.begin_int_data),
  159. SourceLocation::getFromRawEncoding(R.end_int_data));
  160. }
  161. //===----------------------------------------------------------------------===//
  162. // Cursor visitor.
  163. //===----------------------------------------------------------------------===//
  164. static SourceRange getRawCursorExtent(CXCursor C);
  165. static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
  166. RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
  167. return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
  168. }
  169. /// Visit the given cursor and, if requested by the visitor,
  170. /// its children.
  171. ///
  172. /// \param Cursor the cursor to visit.
  173. ///
  174. /// \param CheckedRegionOfInterest if true, then the caller already checked
  175. /// that this cursor is within the region of interest.
  176. ///
  177. /// \returns true if the visitation should be aborted, false if it
  178. /// should continue.
  179. bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
  180. if (clang_isInvalid(Cursor.kind))
  181. return false;
  182. if (clang_isDeclaration(Cursor.kind)) {
  183. const Decl *D = getCursorDecl(Cursor);
  184. if (!D) {
  185. assert(0 && "Invalid declaration cursor");
  186. return true; // abort.
  187. }
  188. // Ignore implicit declarations, unless it's an objc method because
  189. // currently we should report implicit methods for properties when indexing.
  190. if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
  191. return false;
  192. }
  193. // If we have a range of interest, and this cursor doesn't intersect with it,
  194. // we're done.
  195. if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
  196. SourceRange Range = getRawCursorExtent(Cursor);
  197. if (Range.isInvalid() || CompareRegionOfInterest(Range))
  198. return false;
  199. }
  200. switch (Visitor(Cursor, Parent, ClientData)) {
  201. case CXChildVisit_Break:
  202. return true;
  203. case CXChildVisit_Continue:
  204. return false;
  205. case CXChildVisit_Recurse: {
  206. bool ret = VisitChildren(Cursor);
  207. if (PostChildrenVisitor)
  208. if (PostChildrenVisitor(Cursor, ClientData))
  209. return true;
  210. return ret;
  211. }
  212. }
  213. llvm_unreachable("Invalid CXChildVisitResult!");
  214. }
  215. static bool visitPreprocessedEntitiesInRange(SourceRange R,
  216. PreprocessingRecord &PPRec,
  217. CursorVisitor &Visitor) {
  218. SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
  219. FileID FID;
  220. if (!Visitor.shouldVisitIncludedEntities()) {
  221. // If the begin/end of the range lie in the same FileID, do the optimization
  222. // where we skip preprocessed entities that do not come from the same
  223. // FileID.
  224. FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
  225. if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
  226. FID = FileID();
  227. }
  228. const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
  229. return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
  230. PPRec, FID);
  231. }
  232. bool CursorVisitor::visitFileRegion() {
  233. if (RegionOfInterest.isInvalid())
  234. return false;
  235. ASTUnit *Unit = cxtu::getASTUnit(TU);
  236. SourceManager &SM = Unit->getSourceManager();
  237. std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(
  238. SM.getFileLoc(RegionOfInterest.getBegin())),
  239. End = SM.getDecomposedLoc(
  240. SM.getFileLoc(RegionOfInterest.getEnd()));
  241. if (End.first != Begin.first) {
  242. // If the end does not reside in the same file, try to recover by
  243. // picking the end of the file of begin location.
  244. End.first = Begin.first;
  245. End.second = SM.getFileIDSize(Begin.first);
  246. }
  247. assert(Begin.first == End.first);
  248. if (Begin.second > End.second)
  249. return false;
  250. FileID File = Begin.first;
  251. unsigned Offset = Begin.second;
  252. unsigned Length = End.second - Begin.second;
  253. if (!VisitDeclsOnly && !VisitPreprocessorLast)
  254. if (visitPreprocessedEntitiesInRegion())
  255. return true; // visitation break.
  256. if (visitDeclsFromFileRegion(File, Offset, Length))
  257. return true; // visitation break.
  258. if (!VisitDeclsOnly && VisitPreprocessorLast)
  259. return visitPreprocessedEntitiesInRegion();
  260. return false;
  261. }
  262. static bool isInLexicalContext(Decl *D, DeclContext *DC) {
  263. if (!DC)
  264. return false;
  265. for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC;
  266. DeclDC = DeclDC->getLexicalParent()) {
  267. if (DeclDC == DC)
  268. return true;
  269. }
  270. return false;
  271. }
  272. bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset,
  273. unsigned Length) {
  274. ASTUnit *Unit = cxtu::getASTUnit(TU);
  275. SourceManager &SM = Unit->getSourceManager();
  276. SourceRange Range = RegionOfInterest;
  277. SmallVector<Decl *, 16> Decls;
  278. Unit->findFileRegionDecls(File, Offset, Length, Decls);
  279. // If we didn't find any file level decls for the file, try looking at the
  280. // file that it was included from.
  281. while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
  282. bool Invalid = false;
  283. const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
  284. if (Invalid)
  285. return false;
  286. SourceLocation Outer;
  287. if (SLEntry.isFile())
  288. Outer = SLEntry.getFile().getIncludeLoc();
  289. else
  290. Outer = SLEntry.getExpansion().getExpansionLocStart();
  291. if (Outer.isInvalid())
  292. return false;
  293. std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
  294. Length = 0;
  295. Unit->findFileRegionDecls(File, Offset, Length, Decls);
  296. }
  297. assert(!Decls.empty());
  298. bool VisitedAtLeastOnce = false;
  299. DeclContext *CurDC = nullptr;
  300. SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
  301. for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
  302. Decl *D = *DIt;
  303. if (D->getSourceRange().isInvalid())
  304. continue;
  305. if (isInLexicalContext(D, CurDC))
  306. continue;
  307. CurDC = dyn_cast<DeclContext>(D);
  308. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  309. if (!TD->isFreeStanding())
  310. continue;
  311. RangeComparisonResult CompRes =
  312. RangeCompare(SM, D->getSourceRange(), Range);
  313. if (CompRes == RangeBefore)
  314. continue;
  315. if (CompRes == RangeAfter)
  316. break;
  317. assert(CompRes == RangeOverlap);
  318. VisitedAtLeastOnce = true;
  319. if (isa<ObjCContainerDecl>(D)) {
  320. FileDI_current = &DIt;
  321. FileDE_current = DE;
  322. } else {
  323. FileDI_current = nullptr;
  324. }
  325. if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
  326. return true; // visitation break.
  327. }
  328. if (VisitedAtLeastOnce)
  329. return false;
  330. // No Decls overlapped with the range. Move up the lexical context until there
  331. // is a context that contains the range or we reach the translation unit
  332. // level.
  333. DeclContext *DC = DIt == Decls.begin()
  334. ? (*DIt)->getLexicalDeclContext()
  335. : (*(DIt - 1))->getLexicalDeclContext();
  336. while (DC && !DC->isTranslationUnit()) {
  337. Decl *D = cast<Decl>(DC);
  338. SourceRange CurDeclRange = D->getSourceRange();
  339. if (CurDeclRange.isInvalid())
  340. break;
  341. if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
  342. if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
  343. return true; // visitation break.
  344. }
  345. DC = D->getLexicalDeclContext();
  346. }
  347. return false;
  348. }
  349. bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
  350. if (!AU->getPreprocessor().getPreprocessingRecord())
  351. return false;
  352. PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord();
  353. SourceManager &SM = AU->getSourceManager();
  354. if (RegionOfInterest.isValid()) {
  355. SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
  356. SourceLocation B = MappedRange.getBegin();
  357. SourceLocation E = MappedRange.getEnd();
  358. if (AU->isInPreambleFileID(B)) {
  359. if (SM.isLoadedSourceLocation(E))
  360. return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec,
  361. *this);
  362. // Beginning of range lies in the preamble but it also extends beyond
  363. // it into the main file. Split the range into 2 parts, one covering
  364. // the preamble and another covering the main file. This allows subsequent
  365. // calls to visitPreprocessedEntitiesInRange to accept a source range that
  366. // lies in the same FileID, allowing it to skip preprocessed entities that
  367. // do not come from the same FileID.
  368. bool breaked = visitPreprocessedEntitiesInRange(
  369. SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this);
  370. if (breaked)
  371. return true;
  372. return visitPreprocessedEntitiesInRange(
  373. SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this);
  374. }
  375. return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
  376. }
  377. bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
  378. if (OnlyLocalDecls)
  379. return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
  380. PPRec);
  381. return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
  382. }
  383. template <typename InputIterator>
  384. bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
  385. InputIterator Last,
  386. PreprocessingRecord &PPRec,
  387. FileID FID) {
  388. for (; First != Last; ++First) {
  389. if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
  390. continue;
  391. PreprocessedEntity *PPE = *First;
  392. if (!PPE)
  393. continue;
  394. if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
  395. if (Visit(MakeMacroExpansionCursor(ME, TU)))
  396. return true;
  397. continue;
  398. }
  399. if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
  400. if (Visit(MakeMacroDefinitionCursor(MD, TU)))
  401. return true;
  402. continue;
  403. }
  404. if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
  405. if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
  406. return true;
  407. continue;
  408. }
  409. }
  410. return false;
  411. }
  412. /// Visit the children of the given cursor.
  413. ///
  414. /// \returns true if the visitation should be aborted, false if it
  415. /// should continue.
  416. bool CursorVisitor::VisitChildren(CXCursor Cursor) {
  417. if (clang_isReference(Cursor.kind) &&
  418. Cursor.kind != CXCursor_CXXBaseSpecifier) {
  419. // By definition, references have no children.
  420. return false;
  421. }
  422. // Set the Parent field to Cursor, then back to its old value once we're
  423. // done.
  424. SetParentRAII SetParent(Parent, StmtParent, Cursor);
  425. if (clang_isDeclaration(Cursor.kind)) {
  426. Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
  427. if (!D)
  428. return false;
  429. return VisitAttributes(D) || Visit(D);
  430. }
  431. if (clang_isStatement(Cursor.kind)) {
  432. if (const Stmt *S = getCursorStmt(Cursor))
  433. return Visit(S);
  434. return false;
  435. }
  436. if (clang_isExpression(Cursor.kind)) {
  437. if (const Expr *E = getCursorExpr(Cursor))
  438. return Visit(E);
  439. return false;
  440. }
  441. if (clang_isTranslationUnit(Cursor.kind)) {
  442. CXTranslationUnit TU = getCursorTU(Cursor);
  443. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  444. int VisitOrder[2] = {VisitPreprocessorLast, !VisitPreprocessorLast};
  445. for (unsigned I = 0; I != 2; ++I) {
  446. if (VisitOrder[I]) {
  447. if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
  448. RegionOfInterest.isInvalid()) {
  449. for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
  450. TLEnd = CXXUnit->top_level_end();
  451. TL != TLEnd; ++TL) {
  452. const std::optional<bool> V = handleDeclForVisitation(*TL);
  453. if (!V)
  454. continue;
  455. return *V;
  456. }
  457. } else if (VisitDeclContext(
  458. CXXUnit->getASTContext().getTranslationUnitDecl()))
  459. return true;
  460. continue;
  461. }
  462. // Walk the preprocessing record.
  463. if (CXXUnit->getPreprocessor().getPreprocessingRecord())
  464. visitPreprocessedEntitiesInRegion();
  465. }
  466. return false;
  467. }
  468. if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
  469. if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
  470. if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
  471. return Visit(BaseTSInfo->getTypeLoc());
  472. }
  473. }
  474. }
  475. if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
  476. const IBOutletCollectionAttr *A =
  477. cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
  478. if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
  479. return Visit(cxcursor::MakeCursorObjCClassRef(
  480. ObjT->getInterface(),
  481. A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
  482. }
  483. // If pointing inside a macro definition, check if the token is an identifier
  484. // that was ever defined as a macro. In such a case, create a "pseudo" macro
  485. // expansion cursor for that token.
  486. SourceLocation BeginLoc = RegionOfInterest.getBegin();
  487. if (Cursor.kind == CXCursor_MacroDefinition &&
  488. BeginLoc == RegionOfInterest.getEnd()) {
  489. SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
  490. const MacroInfo *MI =
  491. getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
  492. if (MacroDefinitionRecord *MacroDef =
  493. checkForMacroInMacroDefinition(MI, Loc, TU))
  494. return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
  495. }
  496. // Nothing to visit at the moment.
  497. return false;
  498. }
  499. bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
  500. if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
  501. if (Visit(TSInfo->getTypeLoc()))
  502. return true;
  503. if (Stmt *Body = B->getBody())
  504. return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
  505. return false;
  506. }
  507. std::optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
  508. if (RegionOfInterest.isValid()) {
  509. SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
  510. if (Range.isInvalid())
  511. return std::nullopt;
  512. switch (CompareRegionOfInterest(Range)) {
  513. case RangeBefore:
  514. // This declaration comes before the region of interest; skip it.
  515. return std::nullopt;
  516. case RangeAfter:
  517. // This declaration comes after the region of interest; we're done.
  518. return false;
  519. case RangeOverlap:
  520. // This declaration overlaps the region of interest; visit it.
  521. break;
  522. }
  523. }
  524. return true;
  525. }
  526. bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
  527. DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
  528. // FIXME: Eventually remove. This part of a hack to support proper
  529. // iteration over all Decls contained lexically within an ObjC container.
  530. SaveAndRestore DI_saved(DI_current, &I);
  531. SaveAndRestore DE_saved(DE_current, E);
  532. for (; I != E; ++I) {
  533. Decl *D = *I;
  534. if (D->getLexicalDeclContext() != DC)
  535. continue;
  536. // Filter out synthesized property accessor redeclarations.
  537. if (isa<ObjCImplDecl>(DC))
  538. if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
  539. if (OMD->isSynthesizedAccessorStub())
  540. continue;
  541. const std::optional<bool> V = handleDeclForVisitation(D);
  542. if (!V)
  543. continue;
  544. return *V;
  545. }
  546. return false;
  547. }
  548. std::optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
  549. CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
  550. // Ignore synthesized ivars here, otherwise if we have something like:
  551. // @synthesize prop = _prop;
  552. // and '_prop' is not declared, we will encounter a '_prop' ivar before
  553. // encountering the 'prop' synthesize declaration and we will think that
  554. // we passed the region-of-interest.
  555. if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
  556. if (ivarD->getSynthesize())
  557. return std::nullopt;
  558. }
  559. // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
  560. // declarations is a mismatch with the compiler semantics.
  561. if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
  562. auto *ID = cast<ObjCInterfaceDecl>(D);
  563. if (!ID->isThisDeclarationADefinition())
  564. Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
  565. } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
  566. auto *PD = cast<ObjCProtocolDecl>(D);
  567. if (!PD->isThisDeclarationADefinition())
  568. Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
  569. }
  570. const std::optional<bool> V = shouldVisitCursor(Cursor);
  571. if (!V)
  572. return std::nullopt;
  573. if (!*V)
  574. return false;
  575. if (Visit(Cursor, true))
  576. return true;
  577. return std::nullopt;
  578. }
  579. bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  580. llvm_unreachable("Translation units are visited directly by Visit()");
  581. }
  582. bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  583. if (VisitTemplateParameters(D->getTemplateParameters()))
  584. return true;
  585. return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
  586. }
  587. bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
  588. if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
  589. return Visit(TSInfo->getTypeLoc());
  590. return false;
  591. }
  592. bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
  593. if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
  594. return Visit(TSInfo->getTypeLoc());
  595. return false;
  596. }
  597. bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); }
  598. bool CursorVisitor::VisitClassTemplateSpecializationDecl(
  599. ClassTemplateSpecializationDecl *D) {
  600. bool ShouldVisitBody = false;
  601. switch (D->getSpecializationKind()) {
  602. case TSK_Undeclared:
  603. case TSK_ImplicitInstantiation:
  604. // Nothing to visit
  605. return false;
  606. case TSK_ExplicitInstantiationDeclaration:
  607. case TSK_ExplicitInstantiationDefinition:
  608. break;
  609. case TSK_ExplicitSpecialization:
  610. ShouldVisitBody = true;
  611. break;
  612. }
  613. // Visit the template arguments used in the specialization.
  614. if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
  615. TypeLoc TL = SpecType->getTypeLoc();
  616. if (TemplateSpecializationTypeLoc TSTLoc =
  617. TL.getAs<TemplateSpecializationTypeLoc>()) {
  618. for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
  619. if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
  620. return true;
  621. }
  622. }
  623. return ShouldVisitBody && VisitCXXRecordDecl(D);
  624. }
  625. bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
  626. ClassTemplatePartialSpecializationDecl *D) {
  627. // FIXME: Visit the "outer" template parameter lists on the TagDecl
  628. // before visiting these template parameters.
  629. if (VisitTemplateParameters(D->getTemplateParameters()))
  630. return true;
  631. // Visit the partial specialization arguments.
  632. const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
  633. const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
  634. for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
  635. if (VisitTemplateArgumentLoc(TemplateArgs[I]))
  636. return true;
  637. return VisitCXXRecordDecl(D);
  638. }
  639. bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
  640. if (const auto *TC = D->getTypeConstraint()) {
  641. if (VisitTypeConstraint(*TC))
  642. return true;
  643. }
  644. // Visit the default argument.
  645. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
  646. if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
  647. if (Visit(DefArg->getTypeLoc()))
  648. return true;
  649. return false;
  650. }
  651. bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
  652. if (Expr *Init = D->getInitExpr())
  653. return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
  654. return false;
  655. }
  656. bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
  657. unsigned NumParamList = DD->getNumTemplateParameterLists();
  658. for (unsigned i = 0; i < NumParamList; i++) {
  659. TemplateParameterList *Params = DD->getTemplateParameterList(i);
  660. if (VisitTemplateParameters(Params))
  661. return true;
  662. }
  663. if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
  664. if (Visit(TSInfo->getTypeLoc()))
  665. return true;
  666. // Visit the nested-name-specifier, if present.
  667. if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
  668. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  669. return true;
  670. return false;
  671. }
  672. static bool HasTrailingReturnType(FunctionDecl *ND) {
  673. const QualType Ty = ND->getType();
  674. if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
  675. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
  676. return FT->hasTrailingReturn();
  677. }
  678. return false;
  679. }
  680. /// Compare two base or member initializers based on their source order.
  681. static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
  682. CXXCtorInitializer *const *Y) {
  683. return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
  684. }
  685. bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
  686. unsigned NumParamList = ND->getNumTemplateParameterLists();
  687. for (unsigned i = 0; i < NumParamList; i++) {
  688. TemplateParameterList *Params = ND->getTemplateParameterList(i);
  689. if (VisitTemplateParameters(Params))
  690. return true;
  691. }
  692. if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
  693. // Visit the function declaration's syntactic components in the order
  694. // written. This requires a bit of work.
  695. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
  696. FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
  697. const bool HasTrailingRT = HasTrailingReturnType(ND);
  698. // If we have a function declared directly (without the use of a typedef),
  699. // visit just the return type. Otherwise, just visit the function's type
  700. // now.
  701. if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
  702. Visit(FTL.getReturnLoc())) ||
  703. (!FTL && Visit(TL)))
  704. return true;
  705. // Visit the nested-name-specifier, if present.
  706. if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
  707. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  708. return true;
  709. // Visit the declaration name.
  710. if (!isa<CXXDestructorDecl>(ND))
  711. if (VisitDeclarationNameInfo(ND->getNameInfo()))
  712. return true;
  713. // FIXME: Visit explicitly-specified template arguments!
  714. // Visit the function parameters, if we have a function type.
  715. if (FTL && VisitFunctionTypeLoc(FTL, true))
  716. return true;
  717. // Visit the function's trailing return type.
  718. if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
  719. return true;
  720. // FIXME: Attributes?
  721. }
  722. if (auto *E = ND->getTrailingRequiresClause()) {
  723. if (Visit(E))
  724. return true;
  725. }
  726. if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
  727. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
  728. // Find the initializers that were written in the source.
  729. SmallVector<CXXCtorInitializer *, 4> WrittenInits;
  730. for (auto *I : Constructor->inits()) {
  731. if (!I->isWritten())
  732. continue;
  733. WrittenInits.push_back(I);
  734. }
  735. // Sort the initializers in source order
  736. llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
  737. &CompareCXXCtorInitializers);
  738. // Visit the initializers in source order
  739. for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
  740. CXXCtorInitializer *Init = WrittenInits[I];
  741. if (Init->isAnyMemberInitializer()) {
  742. if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
  743. Init->getMemberLocation(), TU)))
  744. return true;
  745. } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
  746. if (Visit(TInfo->getTypeLoc()))
  747. return true;
  748. }
  749. // Visit the initializer value.
  750. if (Expr *Initializer = Init->getInit())
  751. if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
  752. return true;
  753. }
  754. }
  755. if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
  756. return true;
  757. }
  758. return false;
  759. }
  760. bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
  761. if (VisitDeclaratorDecl(D))
  762. return true;
  763. if (Expr *BitWidth = D->getBitWidth())
  764. return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
  765. if (Expr *Init = D->getInClassInitializer())
  766. return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
  767. return false;
  768. }
  769. bool CursorVisitor::VisitVarDecl(VarDecl *D) {
  770. if (VisitDeclaratorDecl(D))
  771. return true;
  772. if (Expr *Init = D->getInit())
  773. return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
  774. return false;
  775. }
  776. bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
  777. if (VisitDeclaratorDecl(D))
  778. return true;
  779. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
  780. if (Expr *DefArg = D->getDefaultArgument())
  781. return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
  782. return false;
  783. }
  784. bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  785. // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
  786. // before visiting these template parameters.
  787. if (VisitTemplateParameters(D->getTemplateParameters()))
  788. return true;
  789. auto *FD = D->getTemplatedDecl();
  790. return VisitAttributes(FD) || VisitFunctionDecl(FD);
  791. }
  792. bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  793. // FIXME: Visit the "outer" template parameter lists on the TagDecl
  794. // before visiting these template parameters.
  795. if (VisitTemplateParameters(D->getTemplateParameters()))
  796. return true;
  797. auto *CD = D->getTemplatedDecl();
  798. return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
  799. }
  800. bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
  801. if (VisitTemplateParameters(D->getTemplateParameters()))
  802. return true;
  803. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
  804. VisitTemplateArgumentLoc(D->getDefaultArgument()))
  805. return true;
  806. return false;
  807. }
  808. bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
  809. // Visit the bound, if it's explicit.
  810. if (D->hasExplicitBound()) {
  811. if (auto TInfo = D->getTypeSourceInfo()) {
  812. if (Visit(TInfo->getTypeLoc()))
  813. return true;
  814. }
  815. }
  816. return false;
  817. }
  818. bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
  819. if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
  820. if (Visit(TSInfo->getTypeLoc()))
  821. return true;
  822. for (const auto *P : ND->parameters()) {
  823. if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
  824. return true;
  825. }
  826. return ND->isThisDeclarationADefinition() &&
  827. Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
  828. }
  829. template <typename DeclIt>
  830. static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
  831. SourceManager &SM, SourceLocation EndLoc,
  832. SmallVectorImpl<Decl *> &Decls) {
  833. DeclIt next = *DI_current;
  834. while (++next != DE_current) {
  835. Decl *D_next = *next;
  836. if (!D_next)
  837. break;
  838. SourceLocation L = D_next->getBeginLoc();
  839. if (!L.isValid())
  840. break;
  841. if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
  842. *DI_current = next;
  843. Decls.push_back(D_next);
  844. continue;
  845. }
  846. break;
  847. }
  848. }
  849. bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
  850. // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
  851. // an @implementation can lexically contain Decls that are not properly
  852. // nested in the AST. When we identify such cases, we need to retrofit
  853. // this nesting here.
  854. if (!DI_current && !FileDI_current)
  855. return VisitDeclContext(D);
  856. // Scan the Decls that immediately come after the container
  857. // in the current DeclContext. If any fall within the
  858. // container's lexical region, stash them into a vector
  859. // for later processing.
  860. SmallVector<Decl *, 24> DeclsInContainer;
  861. SourceLocation EndLoc = D->getSourceRange().getEnd();
  862. SourceManager &SM = AU->getSourceManager();
  863. if (EndLoc.isValid()) {
  864. if (DI_current) {
  865. addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
  866. DeclsInContainer);
  867. } else {
  868. addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
  869. DeclsInContainer);
  870. }
  871. }
  872. // The common case.
  873. if (DeclsInContainer.empty())
  874. return VisitDeclContext(D);
  875. // Get all the Decls in the DeclContext, and sort them with the
  876. // additional ones we've collected. Then visit them.
  877. for (auto *SubDecl : D->decls()) {
  878. if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
  879. SubDecl->getBeginLoc().isInvalid())
  880. continue;
  881. DeclsInContainer.push_back(SubDecl);
  882. }
  883. // Now sort the Decls so that they appear in lexical order.
  884. llvm::sort(DeclsInContainer, [&SM](Decl *A, Decl *B) {
  885. SourceLocation L_A = A->getBeginLoc();
  886. SourceLocation L_B = B->getBeginLoc();
  887. return L_A != L_B
  888. ? SM.isBeforeInTranslationUnit(L_A, L_B)
  889. : SM.isBeforeInTranslationUnit(A->getEndLoc(), B->getEndLoc());
  890. });
  891. // Now visit the decls.
  892. for (SmallVectorImpl<Decl *>::iterator I = DeclsInContainer.begin(),
  893. E = DeclsInContainer.end();
  894. I != E; ++I) {
  895. CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
  896. const std::optional<bool> &V = shouldVisitCursor(Cursor);
  897. if (!V)
  898. continue;
  899. if (!*V)
  900. return false;
  901. if (Visit(Cursor, true))
  902. return true;
  903. }
  904. return false;
  905. }
  906. bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
  907. if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
  908. TU)))
  909. return true;
  910. if (VisitObjCTypeParamList(ND->getTypeParamList()))
  911. return true;
  912. ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
  913. for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
  914. E = ND->protocol_end();
  915. I != E; ++I, ++PL)
  916. if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
  917. return true;
  918. return VisitObjCContainerDecl(ND);
  919. }
  920. bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
  921. if (!PID->isThisDeclarationADefinition())
  922. return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
  923. ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
  924. for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
  925. E = PID->protocol_end();
  926. I != E; ++I, ++PL)
  927. if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
  928. return true;
  929. return VisitObjCContainerDecl(PID);
  930. }
  931. bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
  932. if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
  933. return true;
  934. // FIXME: This implements a workaround with @property declarations also being
  935. // installed in the DeclContext for the @interface. Eventually this code
  936. // should be removed.
  937. ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
  938. if (!CDecl || !CDecl->IsClassExtension())
  939. return false;
  940. ObjCInterfaceDecl *ID = CDecl->getClassInterface();
  941. if (!ID)
  942. return false;
  943. IdentifierInfo *PropertyId = PD->getIdentifier();
  944. ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(
  945. cast<DeclContext>(ID), PropertyId, PD->getQueryKind());
  946. if (!prevDecl)
  947. return false;
  948. // Visit synthesized methods since they will be skipped when visiting
  949. // the @interface.
  950. if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
  951. if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
  952. if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
  953. return true;
  954. if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
  955. if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
  956. if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
  957. return true;
  958. return false;
  959. }
  960. bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
  961. if (!typeParamList)
  962. return false;
  963. for (auto *typeParam : *typeParamList) {
  964. // Visit the type parameter.
  965. if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
  966. return true;
  967. }
  968. return false;
  969. }
  970. bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
  971. if (!D->isThisDeclarationADefinition()) {
  972. // Forward declaration is treated like a reference.
  973. return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
  974. }
  975. // Objective-C type parameters.
  976. if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
  977. return true;
  978. // Issue callbacks for super class.
  979. if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(
  980. D->getSuperClass(), D->getSuperClassLoc(), TU)))
  981. return true;
  982. if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
  983. if (Visit(SuperClassTInfo->getTypeLoc()))
  984. return true;
  985. ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
  986. for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
  987. E = D->protocol_end();
  988. I != E; ++I, ++PL)
  989. if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
  990. return true;
  991. return VisitObjCContainerDecl(D);
  992. }
  993. bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
  994. return VisitObjCContainerDecl(D);
  995. }
  996. bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
  997. // 'ID' could be null when dealing with invalid code.
  998. if (ObjCInterfaceDecl *ID = D->getClassInterface())
  999. if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
  1000. return true;
  1001. return VisitObjCImplDecl(D);
  1002. }
  1003. bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
  1004. #if 0
  1005. // Issue callbacks for super class.
  1006. // FIXME: No source location information!
  1007. if (D->getSuperClass() &&
  1008. Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
  1009. D->getSuperClassLoc(),
  1010. TU)))
  1011. return true;
  1012. #endif
  1013. return VisitObjCImplDecl(D);
  1014. }
  1015. bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
  1016. if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
  1017. if (PD->isIvarNameSpecified())
  1018. return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
  1019. return false;
  1020. }
  1021. bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
  1022. return VisitDeclContext(D);
  1023. }
  1024. bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  1025. // Visit nested-name-specifier.
  1026. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1027. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1028. return true;
  1029. return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
  1030. D->getTargetNameLoc(), TU));
  1031. }
  1032. bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
  1033. // Visit nested-name-specifier.
  1034. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
  1035. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1036. return true;
  1037. }
  1038. if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
  1039. return true;
  1040. return VisitDeclarationNameInfo(D->getNameInfo());
  1041. }
  1042. bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  1043. // Visit nested-name-specifier.
  1044. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1045. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1046. return true;
  1047. return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
  1048. D->getIdentLocation(), TU));
  1049. }
  1050. bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  1051. // Visit nested-name-specifier.
  1052. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
  1053. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1054. return true;
  1055. }
  1056. return VisitDeclarationNameInfo(D->getNameInfo());
  1057. }
  1058. bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
  1059. UnresolvedUsingTypenameDecl *D) {
  1060. // Visit nested-name-specifier.
  1061. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1062. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1063. return true;
  1064. return false;
  1065. }
  1066. bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
  1067. if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
  1068. return true;
  1069. if (StringLiteral *Message = D->getMessage())
  1070. if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
  1071. return true;
  1072. return false;
  1073. }
  1074. bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
  1075. if (NamedDecl *FriendD = D->getFriendDecl()) {
  1076. if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
  1077. return true;
  1078. } else if (TypeSourceInfo *TI = D->getFriendType()) {
  1079. if (Visit(TI->getTypeLoc()))
  1080. return true;
  1081. }
  1082. return false;
  1083. }
  1084. bool CursorVisitor::VisitDecompositionDecl(DecompositionDecl *D) {
  1085. for (auto *B : D->bindings()) {
  1086. if (Visit(MakeCXCursor(B, TU, RegionOfInterest)))
  1087. return true;
  1088. }
  1089. return VisitVarDecl(D);
  1090. }
  1091. bool CursorVisitor::VisitConceptDecl(ConceptDecl *D) {
  1092. if (VisitTemplateParameters(D->getTemplateParameters()))
  1093. return true;
  1094. if (auto *E = D->getConstraintExpr()) {
  1095. if (Visit(MakeCXCursor(E, D, TU, RegionOfInterest)))
  1096. return true;
  1097. }
  1098. return false;
  1099. }
  1100. bool CursorVisitor::VisitTypeConstraint(const TypeConstraint &TC) {
  1101. if (TC.getNestedNameSpecifierLoc()) {
  1102. if (VisitNestedNameSpecifierLoc(TC.getNestedNameSpecifierLoc()))
  1103. return true;
  1104. }
  1105. if (TC.getNamedConcept()) {
  1106. if (Visit(MakeCursorTemplateRef(TC.getNamedConcept(),
  1107. TC.getConceptNameLoc(), TU)))
  1108. return true;
  1109. }
  1110. if (auto Args = TC.getTemplateArgsAsWritten()) {
  1111. for (const auto &Arg : Args->arguments()) {
  1112. if (VisitTemplateArgumentLoc(Arg))
  1113. return true;
  1114. }
  1115. }
  1116. return false;
  1117. }
  1118. bool CursorVisitor::VisitConceptRequirement(const concepts::Requirement &R) {
  1119. using namespace concepts;
  1120. switch (R.getKind()) {
  1121. case Requirement::RK_Type: {
  1122. const TypeRequirement &TR = cast<TypeRequirement>(R);
  1123. if (!TR.isSubstitutionFailure()) {
  1124. if (Visit(TR.getType()->getTypeLoc()))
  1125. return true;
  1126. }
  1127. break;
  1128. }
  1129. case Requirement::RK_Simple:
  1130. case Requirement::RK_Compound: {
  1131. const ExprRequirement &ER = cast<ExprRequirement>(R);
  1132. if (!ER.isExprSubstitutionFailure()) {
  1133. if (Visit(ER.getExpr()))
  1134. return true;
  1135. }
  1136. if (ER.getKind() == Requirement::RK_Compound) {
  1137. const auto &RTR = ER.getReturnTypeRequirement();
  1138. if (RTR.isTypeConstraint()) {
  1139. if (const auto *Cons = RTR.getTypeConstraint())
  1140. VisitTypeConstraint(*Cons);
  1141. }
  1142. }
  1143. break;
  1144. }
  1145. case Requirement::RK_Nested: {
  1146. const NestedRequirement &NR = cast<NestedRequirement>(R);
  1147. if (!NR.hasInvalidConstraint()) {
  1148. if (Visit(NR.getConstraintExpr()))
  1149. return true;
  1150. }
  1151. break;
  1152. }
  1153. }
  1154. return false;
  1155. }
  1156. bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
  1157. switch (Name.getName().getNameKind()) {
  1158. case clang::DeclarationName::Identifier:
  1159. case clang::DeclarationName::CXXLiteralOperatorName:
  1160. case clang::DeclarationName::CXXDeductionGuideName:
  1161. case clang::DeclarationName::CXXOperatorName:
  1162. case clang::DeclarationName::CXXUsingDirective:
  1163. return false;
  1164. case clang::DeclarationName::CXXConstructorName:
  1165. case clang::DeclarationName::CXXDestructorName:
  1166. case clang::DeclarationName::CXXConversionFunctionName:
  1167. if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
  1168. return Visit(TSInfo->getTypeLoc());
  1169. return false;
  1170. case clang::DeclarationName::ObjCZeroArgSelector:
  1171. case clang::DeclarationName::ObjCOneArgSelector:
  1172. case clang::DeclarationName::ObjCMultiArgSelector:
  1173. // FIXME: Per-identifier location info?
  1174. return false;
  1175. }
  1176. llvm_unreachable("Invalid DeclarationName::Kind!");
  1177. }
  1178. bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
  1179. SourceRange Range) {
  1180. // FIXME: This whole routine is a hack to work around the lack of proper
  1181. // source information in nested-name-specifiers (PR5791). Since we do have
  1182. // a beginning source location, we can visit the first component of the
  1183. // nested-name-specifier, if it's a single-token component.
  1184. if (!NNS)
  1185. return false;
  1186. // Get the first component in the nested-name-specifier.
  1187. while (NestedNameSpecifier *Prefix = NNS->getPrefix())
  1188. NNS = Prefix;
  1189. switch (NNS->getKind()) {
  1190. case NestedNameSpecifier::Namespace:
  1191. return Visit(
  1192. MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU));
  1193. case NestedNameSpecifier::NamespaceAlias:
  1194. return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
  1195. Range.getBegin(), TU));
  1196. case NestedNameSpecifier::TypeSpec: {
  1197. // If the type has a form where we know that the beginning of the source
  1198. // range matches up with a reference cursor. Visit the appropriate reference
  1199. // cursor.
  1200. const Type *T = NNS->getAsType();
  1201. if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
  1202. return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
  1203. if (const TagType *Tag = dyn_cast<TagType>(T))
  1204. return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
  1205. if (const TemplateSpecializationType *TST =
  1206. dyn_cast<TemplateSpecializationType>(T))
  1207. return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
  1208. break;
  1209. }
  1210. case NestedNameSpecifier::TypeSpecWithTemplate:
  1211. case NestedNameSpecifier::Global:
  1212. case NestedNameSpecifier::Identifier:
  1213. case NestedNameSpecifier::Super:
  1214. break;
  1215. }
  1216. return false;
  1217. }
  1218. bool CursorVisitor::VisitNestedNameSpecifierLoc(
  1219. NestedNameSpecifierLoc Qualifier) {
  1220. SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
  1221. for (; Qualifier; Qualifier = Qualifier.getPrefix())
  1222. Qualifiers.push_back(Qualifier);
  1223. while (!Qualifiers.empty()) {
  1224. NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
  1225. NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
  1226. switch (NNS->getKind()) {
  1227. case NestedNameSpecifier::Namespace:
  1228. if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
  1229. Q.getLocalBeginLoc(), TU)))
  1230. return true;
  1231. break;
  1232. case NestedNameSpecifier::NamespaceAlias:
  1233. if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
  1234. Q.getLocalBeginLoc(), TU)))
  1235. return true;
  1236. break;
  1237. case NestedNameSpecifier::TypeSpec:
  1238. case NestedNameSpecifier::TypeSpecWithTemplate:
  1239. if (Visit(Q.getTypeLoc()))
  1240. return true;
  1241. break;
  1242. case NestedNameSpecifier::Global:
  1243. case NestedNameSpecifier::Identifier:
  1244. case NestedNameSpecifier::Super:
  1245. break;
  1246. }
  1247. }
  1248. return false;
  1249. }
  1250. bool CursorVisitor::VisitTemplateParameters(
  1251. const TemplateParameterList *Params) {
  1252. if (!Params)
  1253. return false;
  1254. for (TemplateParameterList::const_iterator P = Params->begin(),
  1255. PEnd = Params->end();
  1256. P != PEnd; ++P) {
  1257. if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
  1258. return true;
  1259. }
  1260. if (const auto *E = Params->getRequiresClause()) {
  1261. if (Visit(MakeCXCursor(E, nullptr, TU, RegionOfInterest)))
  1262. return true;
  1263. }
  1264. return false;
  1265. }
  1266. bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
  1267. switch (Name.getKind()) {
  1268. case TemplateName::Template:
  1269. case TemplateName::UsingTemplate:
  1270. case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier.
  1271. return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
  1272. case TemplateName::OverloadedTemplate:
  1273. // Visit the overloaded template set.
  1274. if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
  1275. return true;
  1276. return false;
  1277. case TemplateName::AssumedTemplate:
  1278. // FIXME: Visit DeclarationName?
  1279. return false;
  1280. case TemplateName::DependentTemplate:
  1281. // FIXME: Visit nested-name-specifier.
  1282. return false;
  1283. case TemplateName::SubstTemplateTemplateParm:
  1284. return Visit(MakeCursorTemplateRef(
  1285. Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU));
  1286. case TemplateName::SubstTemplateTemplateParmPack:
  1287. return Visit(MakeCursorTemplateRef(
  1288. Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc,
  1289. TU));
  1290. }
  1291. llvm_unreachable("Invalid TemplateName::Kind!");
  1292. }
  1293. bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
  1294. switch (TAL.getArgument().getKind()) {
  1295. case TemplateArgument::Null:
  1296. case TemplateArgument::Integral:
  1297. case TemplateArgument::Pack:
  1298. return false;
  1299. case TemplateArgument::Type:
  1300. if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
  1301. return Visit(TSInfo->getTypeLoc());
  1302. return false;
  1303. case TemplateArgument::Declaration:
  1304. if (Expr *E = TAL.getSourceDeclExpression())
  1305. return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
  1306. return false;
  1307. case TemplateArgument::NullPtr:
  1308. if (Expr *E = TAL.getSourceNullPtrExpression())
  1309. return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
  1310. return false;
  1311. case TemplateArgument::Expression:
  1312. if (Expr *E = TAL.getSourceExpression())
  1313. return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
  1314. return false;
  1315. case TemplateArgument::Template:
  1316. case TemplateArgument::TemplateExpansion:
  1317. if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
  1318. return true;
  1319. return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
  1320. TAL.getTemplateNameLoc());
  1321. }
  1322. llvm_unreachable("Invalid TemplateArgument::Kind!");
  1323. }
  1324. bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
  1325. return VisitDeclContext(D);
  1326. }
  1327. bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  1328. return Visit(TL.getUnqualifiedLoc());
  1329. }
  1330. bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  1331. ASTContext &Context = AU->getASTContext();
  1332. // Some builtin types (such as Objective-C's "id", "sel", and
  1333. // "Class") have associated declarations. Create cursors for those.
  1334. QualType VisitType;
  1335. switch (TL.getTypePtr()->getKind()) {
  1336. case BuiltinType::Void:
  1337. case BuiltinType::NullPtr:
  1338. case BuiltinType::Dependent:
  1339. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1340. case BuiltinType::Id:
  1341. #include "clang/Basic/OpenCLImageTypes.def"
  1342. #define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) case BuiltinType::Id:
  1343. #include "clang/Basic/OpenCLExtensionTypes.def"
  1344. case BuiltinType::OCLSampler:
  1345. case BuiltinType::OCLEvent:
  1346. case BuiltinType::OCLClkEvent:
  1347. case BuiltinType::OCLQueue:
  1348. case BuiltinType::OCLReserveID:
  1349. #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  1350. #include "clang/Basic/AArch64SVEACLETypes.def"
  1351. #define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
  1352. #include "clang/Basic/PPCTypes.def"
  1353. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  1354. #include "clang/Basic/RISCVVTypes.def"
  1355. #define BUILTIN_TYPE(Id, SingletonId)
  1356. #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  1357. #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  1358. #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
  1359. #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
  1360. #include "clang/AST/BuiltinTypes.def"
  1361. break;
  1362. case BuiltinType::ObjCId:
  1363. VisitType = Context.getObjCIdType();
  1364. break;
  1365. case BuiltinType::ObjCClass:
  1366. VisitType = Context.getObjCClassType();
  1367. break;
  1368. case BuiltinType::ObjCSel:
  1369. VisitType = Context.getObjCSelType();
  1370. break;
  1371. }
  1372. if (!VisitType.isNull()) {
  1373. if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
  1374. return Visit(
  1375. MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU));
  1376. }
  1377. return false;
  1378. }
  1379. bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  1380. return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
  1381. }
  1382. bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  1383. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1384. }
  1385. bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
  1386. if (TL.isDefinition())
  1387. return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
  1388. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1389. }
  1390. bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  1391. if (const auto *TC = TL.getDecl()->getTypeConstraint()) {
  1392. if (VisitTypeConstraint(*TC))
  1393. return true;
  1394. }
  1395. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1396. }
  1397. bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  1398. return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
  1399. }
  1400. bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
  1401. if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
  1402. return true;
  1403. for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
  1404. if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
  1405. TU)))
  1406. return true;
  1407. }
  1408. return false;
  1409. }
  1410. bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  1411. if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
  1412. return true;
  1413. for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
  1414. if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
  1415. return true;
  1416. }
  1417. for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
  1418. if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
  1419. TU)))
  1420. return true;
  1421. }
  1422. return false;
  1423. }
  1424. bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  1425. return Visit(TL.getPointeeLoc());
  1426. }
  1427. bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
  1428. return Visit(TL.getInnerLoc());
  1429. }
  1430. bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
  1431. return Visit(TL.getInnerLoc());
  1432. }
  1433. bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
  1434. return Visit(TL.getPointeeLoc());
  1435. }
  1436. bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  1437. return Visit(TL.getPointeeLoc());
  1438. }
  1439. bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  1440. return Visit(TL.getPointeeLoc());
  1441. }
  1442. bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  1443. return Visit(TL.getPointeeLoc());
  1444. }
  1445. bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  1446. return Visit(TL.getPointeeLoc());
  1447. }
  1448. bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) {
  1449. auto *underlyingDecl = TL.getUnderlyingType()->getAsTagDecl();
  1450. if (underlyingDecl) {
  1451. return Visit(MakeCursorTypeRef(underlyingDecl, TL.getNameLoc(), TU));
  1452. }
  1453. return false;
  1454. }
  1455. bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  1456. return Visit(TL.getModifiedLoc());
  1457. }
  1458. bool CursorVisitor::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
  1459. return Visit(TL.getWrappedLoc());
  1460. }
  1461. bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
  1462. bool SkipResultType) {
  1463. if (!SkipResultType && Visit(TL.getReturnLoc()))
  1464. return true;
  1465. for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
  1466. if (Decl *D = TL.getParam(I))
  1467. if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
  1468. return true;
  1469. return false;
  1470. }
  1471. bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  1472. if (Visit(TL.getElementLoc()))
  1473. return true;
  1474. if (Expr *Size = TL.getSizeExpr())
  1475. return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
  1476. return false;
  1477. }
  1478. bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  1479. return Visit(TL.getOriginalLoc());
  1480. }
  1481. bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  1482. return Visit(TL.getOriginalLoc());
  1483. }
  1484. bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
  1485. DeducedTemplateSpecializationTypeLoc TL) {
  1486. if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
  1487. TL.getTemplateNameLoc()))
  1488. return true;
  1489. return false;
  1490. }
  1491. bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
  1492. TemplateSpecializationTypeLoc TL) {
  1493. // Visit the template name.
  1494. if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
  1495. TL.getTemplateNameLoc()))
  1496. return true;
  1497. // Visit the template arguments.
  1498. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
  1499. if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
  1500. return true;
  1501. return false;
  1502. }
  1503. bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  1504. return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
  1505. }
  1506. bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  1507. if (TypeSourceInfo *TSInfo = TL.getUnmodifiedTInfo())
  1508. return Visit(TSInfo->getTypeLoc());
  1509. return false;
  1510. }
  1511. bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  1512. if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
  1513. return Visit(TSInfo->getTypeLoc());
  1514. return false;
  1515. }
  1516. bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  1517. return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
  1518. }
  1519. bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
  1520. DependentTemplateSpecializationTypeLoc TL) {
  1521. // Visit the nested-name-specifier, if there is one.
  1522. if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
  1523. return true;
  1524. // Visit the template arguments.
  1525. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
  1526. if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
  1527. return true;
  1528. return false;
  1529. }
  1530. bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  1531. if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
  1532. return true;
  1533. return Visit(TL.getNamedTypeLoc());
  1534. }
  1535. bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  1536. return Visit(TL.getPatternLoc());
  1537. }
  1538. bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  1539. if (Expr *E = TL.getUnderlyingExpr())
  1540. return Visit(MakeCXCursor(E, StmtParent, TU));
  1541. return false;
  1542. }
  1543. bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  1544. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1545. }
  1546. bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  1547. return Visit(TL.getValueLoc());
  1548. }
  1549. bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
  1550. return Visit(TL.getValueLoc());
  1551. }
  1552. #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
  1553. bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
  1554. return Visit##PARENT##Loc(TL); \
  1555. }
  1556. DEFAULT_TYPELOC_IMPL(Complex, Type)
  1557. DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
  1558. DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
  1559. DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
  1560. DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
  1561. DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
  1562. DEFAULT_TYPELOC_IMPL(DependentVector, Type)
  1563. DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
  1564. DEFAULT_TYPELOC_IMPL(Vector, Type)
  1565. DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
  1566. DEFAULT_TYPELOC_IMPL(ConstantMatrix, MatrixType)
  1567. DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, MatrixType)
  1568. DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
  1569. DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
  1570. DEFAULT_TYPELOC_IMPL(Record, TagType)
  1571. DEFAULT_TYPELOC_IMPL(Enum, TagType)
  1572. DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
  1573. DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
  1574. DEFAULT_TYPELOC_IMPL(Auto, Type)
  1575. DEFAULT_TYPELOC_IMPL(BitInt, Type)
  1576. DEFAULT_TYPELOC_IMPL(DependentBitInt, Type)
  1577. bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
  1578. // Visit the nested-name-specifier, if present.
  1579. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1580. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1581. return true;
  1582. if (D->isCompleteDefinition()) {
  1583. for (const auto &I : D->bases()) {
  1584. if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
  1585. return true;
  1586. }
  1587. }
  1588. return VisitTagDecl(D);
  1589. }
  1590. bool CursorVisitor::VisitAttributes(Decl *D) {
  1591. for (const auto *I : D->attrs())
  1592. if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
  1593. !I->isImplicit()) &&
  1594. Visit(MakeCXCursor(I, D, TU)))
  1595. return true;
  1596. return false;
  1597. }
  1598. //===----------------------------------------------------------------------===//
  1599. // Data-recursive visitor methods.
  1600. //===----------------------------------------------------------------------===//
  1601. namespace {
  1602. #define DEF_JOB(NAME, DATA, KIND) \
  1603. class NAME : public VisitorJob { \
  1604. public: \
  1605. NAME(const DATA *d, CXCursor parent) \
  1606. : VisitorJob(parent, VisitorJob::KIND, d) {} \
  1607. static bool classof(const VisitorJob *VJ) { \
  1608. return VJ->getKind() == KIND; \
  1609. } \
  1610. const DATA *get() const { return static_cast<const DATA *>(data[0]); } \
  1611. };
  1612. DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
  1613. DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
  1614. DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
  1615. DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
  1616. DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
  1617. DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
  1618. DEF_JOB(ConceptSpecializationExprVisit, ConceptSpecializationExpr,
  1619. ConceptSpecializationExprVisitKind)
  1620. DEF_JOB(RequiresExprVisit, RequiresExpr, RequiresExprVisitKind)
  1621. DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
  1622. #undef DEF_JOB
  1623. class ExplicitTemplateArgsVisit : public VisitorJob {
  1624. public:
  1625. ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
  1626. const TemplateArgumentLoc *End, CXCursor parent)
  1627. : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
  1628. End) {}
  1629. static bool classof(const VisitorJob *VJ) {
  1630. return VJ->getKind() == ExplicitTemplateArgsVisitKind;
  1631. }
  1632. const TemplateArgumentLoc *begin() const {
  1633. return static_cast<const TemplateArgumentLoc *>(data[0]);
  1634. }
  1635. const TemplateArgumentLoc *end() {
  1636. return static_cast<const TemplateArgumentLoc *>(data[1]);
  1637. }
  1638. };
  1639. class DeclVisit : public VisitorJob {
  1640. public:
  1641. DeclVisit(const Decl *D, CXCursor parent, bool isFirst)
  1642. : VisitorJob(parent, VisitorJob::DeclVisitKind, D,
  1643. isFirst ? (void *)1 : (void *)nullptr) {}
  1644. static bool classof(const VisitorJob *VJ) {
  1645. return VJ->getKind() == DeclVisitKind;
  1646. }
  1647. const Decl *get() const { return static_cast<const Decl *>(data[0]); }
  1648. bool isFirst() const { return data[1] != nullptr; }
  1649. };
  1650. class TypeLocVisit : public VisitorJob {
  1651. public:
  1652. TypeLocVisit(TypeLoc tl, CXCursor parent)
  1653. : VisitorJob(parent, VisitorJob::TypeLocVisitKind,
  1654. tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
  1655. static bool classof(const VisitorJob *VJ) {
  1656. return VJ->getKind() == TypeLocVisitKind;
  1657. }
  1658. TypeLoc get() const {
  1659. QualType T = QualType::getFromOpaquePtr(data[0]);
  1660. return TypeLoc(T, const_cast<void *>(data[1]));
  1661. }
  1662. };
  1663. class LabelRefVisit : public VisitorJob {
  1664. public:
  1665. LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
  1666. : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
  1667. labelLoc.getPtrEncoding()) {}
  1668. static bool classof(const VisitorJob *VJ) {
  1669. return VJ->getKind() == VisitorJob::LabelRefVisitKind;
  1670. }
  1671. const LabelDecl *get() const {
  1672. return static_cast<const LabelDecl *>(data[0]);
  1673. }
  1674. SourceLocation getLoc() const {
  1675. return SourceLocation::getFromPtrEncoding(data[1]);
  1676. }
  1677. };
  1678. class NestedNameSpecifierLocVisit : public VisitorJob {
  1679. public:
  1680. NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
  1681. : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
  1682. Qualifier.getNestedNameSpecifier(),
  1683. Qualifier.getOpaqueData()) {}
  1684. static bool classof(const VisitorJob *VJ) {
  1685. return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
  1686. }
  1687. NestedNameSpecifierLoc get() const {
  1688. return NestedNameSpecifierLoc(
  1689. const_cast<NestedNameSpecifier *>(
  1690. static_cast<const NestedNameSpecifier *>(data[0])),
  1691. const_cast<void *>(data[1]));
  1692. }
  1693. };
  1694. class DeclarationNameInfoVisit : public VisitorJob {
  1695. public:
  1696. DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
  1697. : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
  1698. static bool classof(const VisitorJob *VJ) {
  1699. return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
  1700. }
  1701. DeclarationNameInfo get() const {
  1702. const Stmt *S = static_cast<const Stmt *>(data[0]);
  1703. switch (S->getStmtClass()) {
  1704. default:
  1705. llvm_unreachable("Unhandled Stmt");
  1706. case clang::Stmt::MSDependentExistsStmtClass:
  1707. return cast<MSDependentExistsStmt>(S)->getNameInfo();
  1708. case Stmt::CXXDependentScopeMemberExprClass:
  1709. return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
  1710. case Stmt::DependentScopeDeclRefExprClass:
  1711. return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
  1712. case Stmt::OMPCriticalDirectiveClass:
  1713. return cast<OMPCriticalDirective>(S)->getDirectiveName();
  1714. }
  1715. }
  1716. };
  1717. class MemberRefVisit : public VisitorJob {
  1718. public:
  1719. MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
  1720. : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
  1721. L.getPtrEncoding()) {}
  1722. static bool classof(const VisitorJob *VJ) {
  1723. return VJ->getKind() == VisitorJob::MemberRefVisitKind;
  1724. }
  1725. const FieldDecl *get() const {
  1726. return static_cast<const FieldDecl *>(data[0]);
  1727. }
  1728. SourceLocation getLoc() const {
  1729. return SourceLocation::getFromRawEncoding(
  1730. (SourceLocation::UIntTy)(uintptr_t)data[1]);
  1731. }
  1732. };
  1733. class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
  1734. friend class OMPClauseEnqueue;
  1735. VisitorWorkList &WL;
  1736. CXCursor Parent;
  1737. public:
  1738. EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
  1739. : WL(wl), Parent(parent) {}
  1740. void VisitAddrLabelExpr(const AddrLabelExpr *E);
  1741. void VisitBlockExpr(const BlockExpr *B);
  1742. void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  1743. void VisitCompoundStmt(const CompoundStmt *S);
  1744. void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */
  1745. }
  1746. void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
  1747. void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
  1748. void VisitCXXNewExpr(const CXXNewExpr *E);
  1749. void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
  1750. void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
  1751. void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
  1752. void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
  1753. void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  1754. void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
  1755. void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  1756. void VisitCXXCatchStmt(const CXXCatchStmt *S);
  1757. void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
  1758. void VisitDeclRefExpr(const DeclRefExpr *D);
  1759. void VisitDeclStmt(const DeclStmt *S);
  1760. void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
  1761. void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
  1762. void VisitExplicitCastExpr(const ExplicitCastExpr *E);
  1763. void VisitForStmt(const ForStmt *FS);
  1764. void VisitGotoStmt(const GotoStmt *GS);
  1765. void VisitIfStmt(const IfStmt *If);
  1766. void VisitInitListExpr(const InitListExpr *IE);
  1767. void VisitMemberExpr(const MemberExpr *M);
  1768. void VisitOffsetOfExpr(const OffsetOfExpr *E);
  1769. void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
  1770. void VisitObjCMessageExpr(const ObjCMessageExpr *M);
  1771. void VisitOverloadExpr(const OverloadExpr *E);
  1772. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  1773. void VisitStmt(const Stmt *S);
  1774. void VisitSwitchStmt(const SwitchStmt *S);
  1775. void VisitWhileStmt(const WhileStmt *W);
  1776. void VisitTypeTraitExpr(const TypeTraitExpr *E);
  1777. void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
  1778. void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
  1779. void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
  1780. void VisitVAArgExpr(const VAArgExpr *E);
  1781. void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  1782. void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
  1783. void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
  1784. void VisitLambdaExpr(const LambdaExpr *E);
  1785. void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
  1786. void VisitRequiresExpr(const RequiresExpr *E);
  1787. void VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
  1788. void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
  1789. void VisitOMPLoopBasedDirective(const OMPLoopBasedDirective *D);
  1790. void VisitOMPLoopDirective(const OMPLoopDirective *D);
  1791. void VisitOMPParallelDirective(const OMPParallelDirective *D);
  1792. void VisitOMPSimdDirective(const OMPSimdDirective *D);
  1793. void
  1794. VisitOMPLoopTransformationDirective(const OMPLoopTransformationDirective *D);
  1795. void VisitOMPTileDirective(const OMPTileDirective *D);
  1796. void VisitOMPUnrollDirective(const OMPUnrollDirective *D);
  1797. void VisitOMPForDirective(const OMPForDirective *D);
  1798. void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
  1799. void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
  1800. void VisitOMPSectionDirective(const OMPSectionDirective *D);
  1801. void VisitOMPSingleDirective(const OMPSingleDirective *D);
  1802. void VisitOMPMasterDirective(const OMPMasterDirective *D);
  1803. void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
  1804. void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
  1805. void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
  1806. void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
  1807. void VisitOMPParallelMaskedDirective(const OMPParallelMaskedDirective *D);
  1808. void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
  1809. void VisitOMPTaskDirective(const OMPTaskDirective *D);
  1810. void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
  1811. void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
  1812. void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
  1813. void VisitOMPErrorDirective(const OMPErrorDirective *D);
  1814. void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
  1815. void
  1816. VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
  1817. void VisitOMPCancelDirective(const OMPCancelDirective *D);
  1818. void VisitOMPFlushDirective(const OMPFlushDirective *D);
  1819. void VisitOMPDepobjDirective(const OMPDepobjDirective *D);
  1820. void VisitOMPScanDirective(const OMPScanDirective *D);
  1821. void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
  1822. void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
  1823. void VisitOMPTargetDirective(const OMPTargetDirective *D);
  1824. void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
  1825. void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
  1826. void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
  1827. void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
  1828. void
  1829. VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
  1830. void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
  1831. void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
  1832. void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
  1833. void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
  1834. void VisitOMPMaskedTaskLoopDirective(const OMPMaskedTaskLoopDirective *D);
  1835. void
  1836. VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
  1837. void VisitOMPMaskedTaskLoopSimdDirective(
  1838. const OMPMaskedTaskLoopSimdDirective *D);
  1839. void VisitOMPParallelMasterTaskLoopDirective(
  1840. const OMPParallelMasterTaskLoopDirective *D);
  1841. void VisitOMPParallelMaskedTaskLoopDirective(
  1842. const OMPParallelMaskedTaskLoopDirective *D);
  1843. void VisitOMPParallelMasterTaskLoopSimdDirective(
  1844. const OMPParallelMasterTaskLoopSimdDirective *D);
  1845. void VisitOMPParallelMaskedTaskLoopSimdDirective(
  1846. const OMPParallelMaskedTaskLoopSimdDirective *D);
  1847. void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
  1848. void VisitOMPDistributeParallelForDirective(
  1849. const OMPDistributeParallelForDirective *D);
  1850. void VisitOMPDistributeParallelForSimdDirective(
  1851. const OMPDistributeParallelForSimdDirective *D);
  1852. void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
  1853. void VisitOMPTargetParallelForSimdDirective(
  1854. const OMPTargetParallelForSimdDirective *D);
  1855. void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
  1856. void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
  1857. void VisitOMPTeamsDistributeSimdDirective(
  1858. const OMPTeamsDistributeSimdDirective *D);
  1859. void VisitOMPTeamsDistributeParallelForSimdDirective(
  1860. const OMPTeamsDistributeParallelForSimdDirective *D);
  1861. void VisitOMPTeamsDistributeParallelForDirective(
  1862. const OMPTeamsDistributeParallelForDirective *D);
  1863. void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
  1864. void VisitOMPTargetTeamsDistributeDirective(
  1865. const OMPTargetTeamsDistributeDirective *D);
  1866. void VisitOMPTargetTeamsDistributeParallelForDirective(
  1867. const OMPTargetTeamsDistributeParallelForDirective *D);
  1868. void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
  1869. const OMPTargetTeamsDistributeParallelForSimdDirective *D);
  1870. void VisitOMPTargetTeamsDistributeSimdDirective(
  1871. const OMPTargetTeamsDistributeSimdDirective *D);
  1872. private:
  1873. void AddDeclarationNameInfo(const Stmt *S);
  1874. void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
  1875. void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
  1876. unsigned NumTemplateArgs);
  1877. void AddMemberRef(const FieldDecl *D, SourceLocation L);
  1878. void AddStmt(const Stmt *S);
  1879. void AddDecl(const Decl *D, bool isFirst = true);
  1880. void AddTypeLoc(TypeSourceInfo *TI);
  1881. void EnqueueChildren(const Stmt *S);
  1882. void EnqueueChildren(const OMPClause *S);
  1883. };
  1884. } // namespace
  1885. void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
  1886. // 'S' should always be non-null, since it comes from the
  1887. // statement we are visiting.
  1888. WL.push_back(DeclarationNameInfoVisit(S, Parent));
  1889. }
  1890. void EnqueueVisitor::AddNestedNameSpecifierLoc(
  1891. NestedNameSpecifierLoc Qualifier) {
  1892. if (Qualifier)
  1893. WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
  1894. }
  1895. void EnqueueVisitor::AddStmt(const Stmt *S) {
  1896. if (S)
  1897. WL.push_back(StmtVisit(S, Parent));
  1898. }
  1899. void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
  1900. if (D)
  1901. WL.push_back(DeclVisit(D, Parent, isFirst));
  1902. }
  1903. void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
  1904. unsigned NumTemplateArgs) {
  1905. WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
  1906. }
  1907. void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
  1908. if (D)
  1909. WL.push_back(MemberRefVisit(D, L, Parent));
  1910. }
  1911. void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
  1912. if (TI)
  1913. WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
  1914. }
  1915. void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
  1916. unsigned size = WL.size();
  1917. for (const Stmt *SubStmt : S->children()) {
  1918. AddStmt(SubStmt);
  1919. }
  1920. if (size == WL.size())
  1921. return;
  1922. // Now reverse the entries we just added. This will match the DFS
  1923. // ordering performed by the worklist.
  1924. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
  1925. std::reverse(I, E);
  1926. }
  1927. namespace {
  1928. class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
  1929. EnqueueVisitor *Visitor;
  1930. /// Process clauses with list of variables.
  1931. template <typename T> void VisitOMPClauseList(T *Node);
  1932. public:
  1933. OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {}
  1934. #define GEN_CLANG_CLAUSE_CLASS
  1935. #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C);
  1936. #include "llvm/Frontend/OpenMP/OMP.inc"
  1937. void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
  1938. void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
  1939. };
  1940. void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
  1941. const OMPClauseWithPreInit *C) {
  1942. Visitor->AddStmt(C->getPreInitStmt());
  1943. }
  1944. void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
  1945. const OMPClauseWithPostUpdate *C) {
  1946. VisitOMPClauseWithPreInit(C);
  1947. Visitor->AddStmt(C->getPostUpdateExpr());
  1948. }
  1949. void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
  1950. VisitOMPClauseWithPreInit(C);
  1951. Visitor->AddStmt(C->getCondition());
  1952. }
  1953. void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
  1954. Visitor->AddStmt(C->getCondition());
  1955. }
  1956. void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
  1957. VisitOMPClauseWithPreInit(C);
  1958. Visitor->AddStmt(C->getNumThreads());
  1959. }
  1960. void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
  1961. Visitor->AddStmt(C->getSafelen());
  1962. }
  1963. void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
  1964. Visitor->AddStmt(C->getSimdlen());
  1965. }
  1966. void OMPClauseEnqueue::VisitOMPSizesClause(const OMPSizesClause *C) {
  1967. for (auto E : C->getSizesRefs())
  1968. Visitor->AddStmt(E);
  1969. }
  1970. void OMPClauseEnqueue::VisitOMPFullClause(const OMPFullClause *C) {}
  1971. void OMPClauseEnqueue::VisitOMPPartialClause(const OMPPartialClause *C) {
  1972. Visitor->AddStmt(C->getFactor());
  1973. }
  1974. void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
  1975. Visitor->AddStmt(C->getAllocator());
  1976. }
  1977. void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
  1978. Visitor->AddStmt(C->getNumForLoops());
  1979. }
  1980. void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {}
  1981. void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {}
  1982. void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
  1983. VisitOMPClauseWithPreInit(C);
  1984. Visitor->AddStmt(C->getChunkSize());
  1985. }
  1986. void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
  1987. Visitor->AddStmt(C->getNumForLoops());
  1988. }
  1989. void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
  1990. Visitor->AddStmt(C->getEventHandler());
  1991. }
  1992. void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
  1993. void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
  1994. void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
  1995. void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
  1996. void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
  1997. void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
  1998. void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
  1999. void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
  2000. void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
  2001. void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
  2002. void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
  2003. void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
  2004. void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
  2005. void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
  2006. void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
  2007. void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
  2008. void OMPClauseEnqueue::VisitOMPInitClause(const OMPInitClause *C) {
  2009. VisitOMPClauseList(C);
  2010. }
  2011. void OMPClauseEnqueue::VisitOMPUseClause(const OMPUseClause *C) {
  2012. Visitor->AddStmt(C->getInteropVar());
  2013. }
  2014. void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *C) {
  2015. if (C->getInteropVar())
  2016. Visitor->AddStmt(C->getInteropVar());
  2017. }
  2018. void OMPClauseEnqueue::VisitOMPNovariantsClause(const OMPNovariantsClause *C) {
  2019. Visitor->AddStmt(C->getCondition());
  2020. }
  2021. void OMPClauseEnqueue::VisitOMPNocontextClause(const OMPNocontextClause *C) {
  2022. Visitor->AddStmt(C->getCondition());
  2023. }
  2024. void OMPClauseEnqueue::VisitOMPFilterClause(const OMPFilterClause *C) {
  2025. VisitOMPClauseWithPreInit(C);
  2026. Visitor->AddStmt(C->getThreadID());
  2027. }
  2028. void OMPClauseEnqueue::VisitOMPAlignClause(const OMPAlignClause *C) {
  2029. Visitor->AddStmt(C->getAlignment());
  2030. }
  2031. void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
  2032. const OMPUnifiedAddressClause *) {}
  2033. void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
  2034. const OMPUnifiedSharedMemoryClause *) {}
  2035. void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
  2036. const OMPReverseOffloadClause *) {}
  2037. void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
  2038. const OMPDynamicAllocatorsClause *) {}
  2039. void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
  2040. const OMPAtomicDefaultMemOrderClause *) {}
  2041. void OMPClauseEnqueue::VisitOMPAtClause(const OMPAtClause *) {}
  2042. void OMPClauseEnqueue::VisitOMPSeverityClause(const OMPSeverityClause *) {}
  2043. void OMPClauseEnqueue::VisitOMPMessageClause(const OMPMessageClause *) {}
  2044. void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
  2045. Visitor->AddStmt(C->getDevice());
  2046. }
  2047. void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
  2048. VisitOMPClauseWithPreInit(C);
  2049. Visitor->AddStmt(C->getNumTeams());
  2050. }
  2051. void OMPClauseEnqueue::VisitOMPThreadLimitClause(
  2052. const OMPThreadLimitClause *C) {
  2053. VisitOMPClauseWithPreInit(C);
  2054. Visitor->AddStmt(C->getThreadLimit());
  2055. }
  2056. void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
  2057. Visitor->AddStmt(C->getPriority());
  2058. }
  2059. void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
  2060. Visitor->AddStmt(C->getGrainsize());
  2061. }
  2062. void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
  2063. Visitor->AddStmt(C->getNumTasks());
  2064. }
  2065. void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
  2066. Visitor->AddStmt(C->getHint());
  2067. }
  2068. template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
  2069. for (const auto *I : Node->varlists()) {
  2070. Visitor->AddStmt(I);
  2071. }
  2072. }
  2073. void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
  2074. VisitOMPClauseList(C);
  2075. }
  2076. void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
  2077. VisitOMPClauseList(C);
  2078. }
  2079. void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
  2080. VisitOMPClauseList(C);
  2081. Visitor->AddStmt(C->getAllocator());
  2082. }
  2083. void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
  2084. VisitOMPClauseList(C);
  2085. for (const auto *E : C->private_copies()) {
  2086. Visitor->AddStmt(E);
  2087. }
  2088. }
  2089. void OMPClauseEnqueue::VisitOMPFirstprivateClause(
  2090. const OMPFirstprivateClause *C) {
  2091. VisitOMPClauseList(C);
  2092. VisitOMPClauseWithPreInit(C);
  2093. for (const auto *E : C->private_copies()) {
  2094. Visitor->AddStmt(E);
  2095. }
  2096. for (const auto *E : C->inits()) {
  2097. Visitor->AddStmt(E);
  2098. }
  2099. }
  2100. void OMPClauseEnqueue::VisitOMPLastprivateClause(
  2101. const OMPLastprivateClause *C) {
  2102. VisitOMPClauseList(C);
  2103. VisitOMPClauseWithPostUpdate(C);
  2104. for (auto *E : C->private_copies()) {
  2105. Visitor->AddStmt(E);
  2106. }
  2107. for (auto *E : C->source_exprs()) {
  2108. Visitor->AddStmt(E);
  2109. }
  2110. for (auto *E : C->destination_exprs()) {
  2111. Visitor->AddStmt(E);
  2112. }
  2113. for (auto *E : C->assignment_ops()) {
  2114. Visitor->AddStmt(E);
  2115. }
  2116. }
  2117. void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
  2118. VisitOMPClauseList(C);
  2119. }
  2120. void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
  2121. VisitOMPClauseList(C);
  2122. VisitOMPClauseWithPostUpdate(C);
  2123. for (auto *E : C->privates()) {
  2124. Visitor->AddStmt(E);
  2125. }
  2126. for (auto *E : C->lhs_exprs()) {
  2127. Visitor->AddStmt(E);
  2128. }
  2129. for (auto *E : C->rhs_exprs()) {
  2130. Visitor->AddStmt(E);
  2131. }
  2132. for (auto *E : C->reduction_ops()) {
  2133. Visitor->AddStmt(E);
  2134. }
  2135. if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
  2136. for (auto *E : C->copy_ops()) {
  2137. Visitor->AddStmt(E);
  2138. }
  2139. for (auto *E : C->copy_array_temps()) {
  2140. Visitor->AddStmt(E);
  2141. }
  2142. for (auto *E : C->copy_array_elems()) {
  2143. Visitor->AddStmt(E);
  2144. }
  2145. }
  2146. }
  2147. void OMPClauseEnqueue::VisitOMPTaskReductionClause(
  2148. const OMPTaskReductionClause *C) {
  2149. VisitOMPClauseList(C);
  2150. VisitOMPClauseWithPostUpdate(C);
  2151. for (auto *E : C->privates()) {
  2152. Visitor->AddStmt(E);
  2153. }
  2154. for (auto *E : C->lhs_exprs()) {
  2155. Visitor->AddStmt(E);
  2156. }
  2157. for (auto *E : C->rhs_exprs()) {
  2158. Visitor->AddStmt(E);
  2159. }
  2160. for (auto *E : C->reduction_ops()) {
  2161. Visitor->AddStmt(E);
  2162. }
  2163. }
  2164. void OMPClauseEnqueue::VisitOMPInReductionClause(
  2165. const OMPInReductionClause *C) {
  2166. VisitOMPClauseList(C);
  2167. VisitOMPClauseWithPostUpdate(C);
  2168. for (auto *E : C->privates()) {
  2169. Visitor->AddStmt(E);
  2170. }
  2171. for (auto *E : C->lhs_exprs()) {
  2172. Visitor->AddStmt(E);
  2173. }
  2174. for (auto *E : C->rhs_exprs()) {
  2175. Visitor->AddStmt(E);
  2176. }
  2177. for (auto *E : C->reduction_ops()) {
  2178. Visitor->AddStmt(E);
  2179. }
  2180. for (auto *E : C->taskgroup_descriptors())
  2181. Visitor->AddStmt(E);
  2182. }
  2183. void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
  2184. VisitOMPClauseList(C);
  2185. VisitOMPClauseWithPostUpdate(C);
  2186. for (const auto *E : C->privates()) {
  2187. Visitor->AddStmt(E);
  2188. }
  2189. for (const auto *E : C->inits()) {
  2190. Visitor->AddStmt(E);
  2191. }
  2192. for (const auto *E : C->updates()) {
  2193. Visitor->AddStmt(E);
  2194. }
  2195. for (const auto *E : C->finals()) {
  2196. Visitor->AddStmt(E);
  2197. }
  2198. Visitor->AddStmt(C->getStep());
  2199. Visitor->AddStmt(C->getCalcStep());
  2200. }
  2201. void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
  2202. VisitOMPClauseList(C);
  2203. Visitor->AddStmt(C->getAlignment());
  2204. }
  2205. void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
  2206. VisitOMPClauseList(C);
  2207. for (auto *E : C->source_exprs()) {
  2208. Visitor->AddStmt(E);
  2209. }
  2210. for (auto *E : C->destination_exprs()) {
  2211. Visitor->AddStmt(E);
  2212. }
  2213. for (auto *E : C->assignment_ops()) {
  2214. Visitor->AddStmt(E);
  2215. }
  2216. }
  2217. void OMPClauseEnqueue::VisitOMPCopyprivateClause(
  2218. const OMPCopyprivateClause *C) {
  2219. VisitOMPClauseList(C);
  2220. for (auto *E : C->source_exprs()) {
  2221. Visitor->AddStmt(E);
  2222. }
  2223. for (auto *E : C->destination_exprs()) {
  2224. Visitor->AddStmt(E);
  2225. }
  2226. for (auto *E : C->assignment_ops()) {
  2227. Visitor->AddStmt(E);
  2228. }
  2229. }
  2230. void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
  2231. VisitOMPClauseList(C);
  2232. }
  2233. void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
  2234. Visitor->AddStmt(C->getDepobj());
  2235. }
  2236. void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
  2237. VisitOMPClauseList(C);
  2238. }
  2239. void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
  2240. VisitOMPClauseList(C);
  2241. }
  2242. void OMPClauseEnqueue::VisitOMPDistScheduleClause(
  2243. const OMPDistScheduleClause *C) {
  2244. VisitOMPClauseWithPreInit(C);
  2245. Visitor->AddStmt(C->getChunkSize());
  2246. }
  2247. void OMPClauseEnqueue::VisitOMPDefaultmapClause(
  2248. const OMPDefaultmapClause * /*C*/) {}
  2249. void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
  2250. VisitOMPClauseList(C);
  2251. }
  2252. void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
  2253. VisitOMPClauseList(C);
  2254. }
  2255. void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(
  2256. const OMPUseDevicePtrClause *C) {
  2257. VisitOMPClauseList(C);
  2258. }
  2259. void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause(
  2260. const OMPUseDeviceAddrClause *C) {
  2261. VisitOMPClauseList(C);
  2262. }
  2263. void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(
  2264. const OMPIsDevicePtrClause *C) {
  2265. VisitOMPClauseList(C);
  2266. }
  2267. void OMPClauseEnqueue::VisitOMPHasDeviceAddrClause(
  2268. const OMPHasDeviceAddrClause *C) {
  2269. VisitOMPClauseList(C);
  2270. }
  2271. void OMPClauseEnqueue::VisitOMPNontemporalClause(
  2272. const OMPNontemporalClause *C) {
  2273. VisitOMPClauseList(C);
  2274. for (const auto *E : C->private_refs())
  2275. Visitor->AddStmt(E);
  2276. }
  2277. void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
  2278. void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause(
  2279. const OMPUsesAllocatorsClause *C) {
  2280. for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
  2281. const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I);
  2282. Visitor->AddStmt(D.Allocator);
  2283. Visitor->AddStmt(D.AllocatorTraits);
  2284. }
  2285. }
  2286. void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) {
  2287. Visitor->AddStmt(C->getModifier());
  2288. for (const Expr *E : C->varlists())
  2289. Visitor->AddStmt(E);
  2290. }
  2291. void OMPClauseEnqueue::VisitOMPBindClause(const OMPBindClause *C) {}
  2292. void OMPClauseEnqueue::VisitOMPXDynCGroupMemClause(
  2293. const OMPXDynCGroupMemClause *C) {
  2294. VisitOMPClauseWithPreInit(C);
  2295. Visitor->AddStmt(C->getSize());
  2296. }
  2297. } // namespace
  2298. void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
  2299. unsigned size = WL.size();
  2300. OMPClauseEnqueue Visitor(this);
  2301. Visitor.Visit(S);
  2302. if (size == WL.size())
  2303. return;
  2304. // Now reverse the entries we just added. This will match the DFS
  2305. // ordering performed by the worklist.
  2306. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
  2307. std::reverse(I, E);
  2308. }
  2309. void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
  2310. WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
  2311. }
  2312. void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
  2313. AddDecl(B->getBlockDecl());
  2314. }
  2315. void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2316. EnqueueChildren(E);
  2317. AddTypeLoc(E->getTypeSourceInfo());
  2318. }
  2319. void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
  2320. for (auto &I : llvm::reverse(S->body()))
  2321. AddStmt(I);
  2322. }
  2323. void EnqueueVisitor::VisitMSDependentExistsStmt(
  2324. const MSDependentExistsStmt *S) {
  2325. AddStmt(S->getSubStmt());
  2326. AddDeclarationNameInfo(S);
  2327. if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
  2328. AddNestedNameSpecifierLoc(QualifierLoc);
  2329. }
  2330. void EnqueueVisitor::VisitCXXDependentScopeMemberExpr(
  2331. const CXXDependentScopeMemberExpr *E) {
  2332. if (E->hasExplicitTemplateArgs())
  2333. AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
  2334. AddDeclarationNameInfo(E);
  2335. if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
  2336. AddNestedNameSpecifierLoc(QualifierLoc);
  2337. if (!E->isImplicitAccess())
  2338. AddStmt(E->getBase());
  2339. }
  2340. void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
  2341. // Enqueue the initializer , if any.
  2342. AddStmt(E->getInitializer());
  2343. // Enqueue the array size, if any.
  2344. AddStmt(E->getArraySize().value_or(nullptr));
  2345. // Enqueue the allocated type.
  2346. AddTypeLoc(E->getAllocatedTypeSourceInfo());
  2347. // Enqueue the placement arguments.
  2348. for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
  2349. AddStmt(E->getPlacementArg(I - 1));
  2350. }
  2351. void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
  2352. for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
  2353. AddStmt(CE->getArg(I - 1));
  2354. AddStmt(CE->getCallee());
  2355. AddStmt(CE->getArg(0));
  2356. }
  2357. void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
  2358. const CXXPseudoDestructorExpr *E) {
  2359. // Visit the name of the type being destroyed.
  2360. AddTypeLoc(E->getDestroyedTypeInfo());
  2361. // Visit the scope type that looks disturbingly like the nested-name-specifier
  2362. // but isn't.
  2363. AddTypeLoc(E->getScopeTypeInfo());
  2364. // Visit the nested-name-specifier.
  2365. if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
  2366. AddNestedNameSpecifierLoc(QualifierLoc);
  2367. // Visit base expression.
  2368. AddStmt(E->getBase());
  2369. }
  2370. void EnqueueVisitor::VisitCXXScalarValueInitExpr(
  2371. const CXXScalarValueInitExpr *E) {
  2372. AddTypeLoc(E->getTypeSourceInfo());
  2373. }
  2374. void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
  2375. const CXXTemporaryObjectExpr *E) {
  2376. EnqueueChildren(E);
  2377. AddTypeLoc(E->getTypeSourceInfo());
  2378. }
  2379. void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  2380. EnqueueChildren(E);
  2381. if (E->isTypeOperand())
  2382. AddTypeLoc(E->getTypeOperandSourceInfo());
  2383. }
  2384. void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
  2385. const CXXUnresolvedConstructExpr *E) {
  2386. EnqueueChildren(E);
  2387. AddTypeLoc(E->getTypeSourceInfo());
  2388. }
  2389. void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  2390. EnqueueChildren(E);
  2391. if (E->isTypeOperand())
  2392. AddTypeLoc(E->getTypeOperandSourceInfo());
  2393. }
  2394. void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
  2395. EnqueueChildren(S);
  2396. AddDecl(S->getExceptionDecl());
  2397. }
  2398. void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  2399. AddStmt(S->getBody());
  2400. AddStmt(S->getRangeInit());
  2401. AddDecl(S->getLoopVariable());
  2402. }
  2403. void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
  2404. if (DR->hasExplicitTemplateArgs())
  2405. AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
  2406. WL.push_back(DeclRefExprParts(DR, Parent));
  2407. }
  2408. void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
  2409. const DependentScopeDeclRefExpr *E) {
  2410. if (E->hasExplicitTemplateArgs())
  2411. AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
  2412. AddDeclarationNameInfo(E);
  2413. AddNestedNameSpecifierLoc(E->getQualifierLoc());
  2414. }
  2415. void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
  2416. unsigned size = WL.size();
  2417. bool isFirst = true;
  2418. for (const auto *D : S->decls()) {
  2419. AddDecl(D, isFirst);
  2420. isFirst = false;
  2421. }
  2422. if (size == WL.size())
  2423. return;
  2424. // Now reverse the entries we just added. This will match the DFS
  2425. // ordering performed by the worklist.
  2426. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
  2427. std::reverse(I, E);
  2428. }
  2429. void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
  2430. AddStmt(E->getInit());
  2431. for (const DesignatedInitExpr::Designator &D :
  2432. llvm::reverse(E->designators())) {
  2433. if (D.isFieldDesignator()) {
  2434. if (FieldDecl *Field = D.getField())
  2435. AddMemberRef(Field, D.getFieldLoc());
  2436. continue;
  2437. }
  2438. if (D.isArrayDesignator()) {
  2439. AddStmt(E->getArrayIndex(D));
  2440. continue;
  2441. }
  2442. assert(D.isArrayRangeDesignator() && "Unknown designator kind");
  2443. AddStmt(E->getArrayRangeEnd(D));
  2444. AddStmt(E->getArrayRangeStart(D));
  2445. }
  2446. }
  2447. void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
  2448. EnqueueChildren(E);
  2449. AddTypeLoc(E->getTypeInfoAsWritten());
  2450. }
  2451. void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
  2452. AddStmt(FS->getBody());
  2453. AddStmt(FS->getInc());
  2454. AddStmt(FS->getCond());
  2455. AddDecl(FS->getConditionVariable());
  2456. AddStmt(FS->getInit());
  2457. }
  2458. void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
  2459. WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
  2460. }
  2461. void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
  2462. AddStmt(If->getElse());
  2463. AddStmt(If->getThen());
  2464. AddStmt(If->getCond());
  2465. AddStmt(If->getInit());
  2466. AddDecl(If->getConditionVariable());
  2467. }
  2468. void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
  2469. // We care about the syntactic form of the initializer list, only.
  2470. if (InitListExpr *Syntactic = IE->getSyntacticForm())
  2471. IE = Syntactic;
  2472. EnqueueChildren(IE);
  2473. }
  2474. void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
  2475. WL.push_back(MemberExprParts(M, Parent));
  2476. // If the base of the member access expression is an implicit 'this', don't
  2477. // visit it.
  2478. // FIXME: If we ever want to show these implicit accesses, this will be
  2479. // unfortunate. However, clang_getCursor() relies on this behavior.
  2480. if (M->isImplicitAccess())
  2481. return;
  2482. // Ignore base anonymous struct/union fields, otherwise they will shadow the
  2483. // real field that we are interested in.
  2484. if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
  2485. if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
  2486. if (FD->isAnonymousStructOrUnion()) {
  2487. AddStmt(SubME->getBase());
  2488. return;
  2489. }
  2490. }
  2491. }
  2492. AddStmt(M->getBase());
  2493. }
  2494. void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
  2495. AddTypeLoc(E->getEncodedTypeSourceInfo());
  2496. }
  2497. void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
  2498. EnqueueChildren(M);
  2499. AddTypeLoc(M->getClassReceiverTypeInfo());
  2500. }
  2501. void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
  2502. // Visit the components of the offsetof expression.
  2503. for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
  2504. const OffsetOfNode &Node = E->getComponent(I - 1);
  2505. switch (Node.getKind()) {
  2506. case OffsetOfNode::Array:
  2507. AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
  2508. break;
  2509. case OffsetOfNode::Field:
  2510. AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
  2511. break;
  2512. case OffsetOfNode::Identifier:
  2513. case OffsetOfNode::Base:
  2514. continue;
  2515. }
  2516. }
  2517. // Visit the type into which we're computing the offset.
  2518. AddTypeLoc(E->getTypeSourceInfo());
  2519. }
  2520. void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
  2521. if (E->hasExplicitTemplateArgs())
  2522. AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
  2523. WL.push_back(OverloadExprParts(E, Parent));
  2524. }
  2525. void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
  2526. const UnaryExprOrTypeTraitExpr *E) {
  2527. EnqueueChildren(E);
  2528. if (E->isArgumentType())
  2529. AddTypeLoc(E->getArgumentTypeInfo());
  2530. }
  2531. void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); }
  2532. void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
  2533. AddStmt(S->getBody());
  2534. AddStmt(S->getCond());
  2535. AddDecl(S->getConditionVariable());
  2536. }
  2537. void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
  2538. AddStmt(W->getBody());
  2539. AddStmt(W->getCond());
  2540. AddDecl(W->getConditionVariable());
  2541. }
  2542. void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
  2543. for (unsigned I = E->getNumArgs(); I > 0; --I)
  2544. AddTypeLoc(E->getArg(I - 1));
  2545. }
  2546. void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  2547. AddTypeLoc(E->getQueriedTypeSourceInfo());
  2548. }
  2549. void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  2550. EnqueueChildren(E);
  2551. }
  2552. void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
  2553. VisitOverloadExpr(U);
  2554. if (!U->isImplicitAccess())
  2555. AddStmt(U->getBase());
  2556. }
  2557. void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
  2558. AddStmt(E->getSubExpr());
  2559. AddTypeLoc(E->getWrittenTypeInfo());
  2560. }
  2561. void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  2562. WL.push_back(SizeOfPackExprParts(E, Parent));
  2563. }
  2564. void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  2565. // If the opaque value has a source expression, just transparently
  2566. // visit that. This is useful for (e.g.) pseudo-object expressions.
  2567. if (Expr *SourceExpr = E->getSourceExpr())
  2568. return Visit(SourceExpr);
  2569. }
  2570. void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
  2571. AddStmt(E->getBody());
  2572. WL.push_back(LambdaExprParts(E, Parent));
  2573. }
  2574. void EnqueueVisitor::VisitConceptSpecializationExpr(
  2575. const ConceptSpecializationExpr *E) {
  2576. WL.push_back(ConceptSpecializationExprVisit(E, Parent));
  2577. }
  2578. void EnqueueVisitor::VisitRequiresExpr(const RequiresExpr *E) {
  2579. WL.push_back(RequiresExprVisit(E, Parent));
  2580. for (ParmVarDecl *VD : E->getLocalParameters())
  2581. AddDecl(VD);
  2582. }
  2583. void EnqueueVisitor::VisitCXXParenListInitExpr(const CXXParenListInitExpr *E) {
  2584. EnqueueChildren(E);
  2585. }
  2586. void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
  2587. // Treat the expression like its syntactic form.
  2588. Visit(E->getSyntacticForm());
  2589. }
  2590. void EnqueueVisitor::VisitOMPExecutableDirective(
  2591. const OMPExecutableDirective *D) {
  2592. EnqueueChildren(D);
  2593. for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
  2594. E = D->clauses().end();
  2595. I != E; ++I)
  2596. EnqueueChildren(*I);
  2597. }
  2598. void EnqueueVisitor::VisitOMPLoopBasedDirective(
  2599. const OMPLoopBasedDirective *D) {
  2600. VisitOMPExecutableDirective(D);
  2601. }
  2602. void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
  2603. VisitOMPLoopBasedDirective(D);
  2604. }
  2605. void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
  2606. VisitOMPExecutableDirective(D);
  2607. }
  2608. void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
  2609. VisitOMPLoopDirective(D);
  2610. }
  2611. void EnqueueVisitor::VisitOMPLoopTransformationDirective(
  2612. const OMPLoopTransformationDirective *D) {
  2613. VisitOMPLoopBasedDirective(D);
  2614. }
  2615. void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) {
  2616. VisitOMPLoopTransformationDirective(D);
  2617. }
  2618. void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) {
  2619. VisitOMPLoopTransformationDirective(D);
  2620. }
  2621. void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
  2622. VisitOMPLoopDirective(D);
  2623. }
  2624. void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
  2625. VisitOMPLoopDirective(D);
  2626. }
  2627. void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
  2628. VisitOMPExecutableDirective(D);
  2629. }
  2630. void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
  2631. VisitOMPExecutableDirective(D);
  2632. }
  2633. void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
  2634. VisitOMPExecutableDirective(D);
  2635. }
  2636. void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
  2637. VisitOMPExecutableDirective(D);
  2638. }
  2639. void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
  2640. VisitOMPExecutableDirective(D);
  2641. AddDeclarationNameInfo(D);
  2642. }
  2643. void EnqueueVisitor::VisitOMPParallelForDirective(
  2644. const OMPParallelForDirective *D) {
  2645. VisitOMPLoopDirective(D);
  2646. }
  2647. void EnqueueVisitor::VisitOMPParallelForSimdDirective(
  2648. const OMPParallelForSimdDirective *D) {
  2649. VisitOMPLoopDirective(D);
  2650. }
  2651. void EnqueueVisitor::VisitOMPParallelMasterDirective(
  2652. const OMPParallelMasterDirective *D) {
  2653. VisitOMPExecutableDirective(D);
  2654. }
  2655. void EnqueueVisitor::VisitOMPParallelMaskedDirective(
  2656. const OMPParallelMaskedDirective *D) {
  2657. VisitOMPExecutableDirective(D);
  2658. }
  2659. void EnqueueVisitor::VisitOMPParallelSectionsDirective(
  2660. const OMPParallelSectionsDirective *D) {
  2661. VisitOMPExecutableDirective(D);
  2662. }
  2663. void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
  2664. VisitOMPExecutableDirective(D);
  2665. }
  2666. void EnqueueVisitor::VisitOMPTaskyieldDirective(
  2667. const OMPTaskyieldDirective *D) {
  2668. VisitOMPExecutableDirective(D);
  2669. }
  2670. void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
  2671. VisitOMPExecutableDirective(D);
  2672. }
  2673. void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
  2674. VisitOMPExecutableDirective(D);
  2675. }
  2676. void EnqueueVisitor::VisitOMPErrorDirective(const OMPErrorDirective *D) {
  2677. VisitOMPExecutableDirective(D);
  2678. }
  2679. void EnqueueVisitor::VisitOMPTaskgroupDirective(
  2680. const OMPTaskgroupDirective *D) {
  2681. VisitOMPExecutableDirective(D);
  2682. if (const Expr *E = D->getReductionRef())
  2683. VisitStmt(E);
  2684. }
  2685. void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
  2686. VisitOMPExecutableDirective(D);
  2687. }
  2688. void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
  2689. VisitOMPExecutableDirective(D);
  2690. }
  2691. void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
  2692. VisitOMPExecutableDirective(D);
  2693. }
  2694. void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
  2695. VisitOMPExecutableDirective(D);
  2696. }
  2697. void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
  2698. VisitOMPExecutableDirective(D);
  2699. }
  2700. void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
  2701. VisitOMPExecutableDirective(D);
  2702. }
  2703. void EnqueueVisitor::VisitOMPTargetDataDirective(
  2704. const OMPTargetDataDirective *D) {
  2705. VisitOMPExecutableDirective(D);
  2706. }
  2707. void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
  2708. const OMPTargetEnterDataDirective *D) {
  2709. VisitOMPExecutableDirective(D);
  2710. }
  2711. void EnqueueVisitor::VisitOMPTargetExitDataDirective(
  2712. const OMPTargetExitDataDirective *D) {
  2713. VisitOMPExecutableDirective(D);
  2714. }
  2715. void EnqueueVisitor::VisitOMPTargetParallelDirective(
  2716. const OMPTargetParallelDirective *D) {
  2717. VisitOMPExecutableDirective(D);
  2718. }
  2719. void EnqueueVisitor::VisitOMPTargetParallelForDirective(
  2720. const OMPTargetParallelForDirective *D) {
  2721. VisitOMPLoopDirective(D);
  2722. }
  2723. void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
  2724. VisitOMPExecutableDirective(D);
  2725. }
  2726. void EnqueueVisitor::VisitOMPCancellationPointDirective(
  2727. const OMPCancellationPointDirective *D) {
  2728. VisitOMPExecutableDirective(D);
  2729. }
  2730. void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
  2731. VisitOMPExecutableDirective(D);
  2732. }
  2733. void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
  2734. VisitOMPLoopDirective(D);
  2735. }
  2736. void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
  2737. const OMPTaskLoopSimdDirective *D) {
  2738. VisitOMPLoopDirective(D);
  2739. }
  2740. void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
  2741. const OMPMasterTaskLoopDirective *D) {
  2742. VisitOMPLoopDirective(D);
  2743. }
  2744. void EnqueueVisitor::VisitOMPMaskedTaskLoopDirective(
  2745. const OMPMaskedTaskLoopDirective *D) {
  2746. VisitOMPLoopDirective(D);
  2747. }
  2748. void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
  2749. const OMPMasterTaskLoopSimdDirective *D) {
  2750. VisitOMPLoopDirective(D);
  2751. }
  2752. void EnqueueVisitor::VisitOMPMaskedTaskLoopSimdDirective(
  2753. const OMPMaskedTaskLoopSimdDirective *D) {
  2754. VisitOMPLoopDirective(D);
  2755. }
  2756. void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
  2757. const OMPParallelMasterTaskLoopDirective *D) {
  2758. VisitOMPLoopDirective(D);
  2759. }
  2760. void EnqueueVisitor::VisitOMPParallelMaskedTaskLoopDirective(
  2761. const OMPParallelMaskedTaskLoopDirective *D) {
  2762. VisitOMPLoopDirective(D);
  2763. }
  2764. void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
  2765. const OMPParallelMasterTaskLoopSimdDirective *D) {
  2766. VisitOMPLoopDirective(D);
  2767. }
  2768. void EnqueueVisitor::VisitOMPParallelMaskedTaskLoopSimdDirective(
  2769. const OMPParallelMaskedTaskLoopSimdDirective *D) {
  2770. VisitOMPLoopDirective(D);
  2771. }
  2772. void EnqueueVisitor::VisitOMPDistributeDirective(
  2773. const OMPDistributeDirective *D) {
  2774. VisitOMPLoopDirective(D);
  2775. }
  2776. void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
  2777. const OMPDistributeParallelForDirective *D) {
  2778. VisitOMPLoopDirective(D);
  2779. }
  2780. void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
  2781. const OMPDistributeParallelForSimdDirective *D) {
  2782. VisitOMPLoopDirective(D);
  2783. }
  2784. void EnqueueVisitor::VisitOMPDistributeSimdDirective(
  2785. const OMPDistributeSimdDirective *D) {
  2786. VisitOMPLoopDirective(D);
  2787. }
  2788. void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
  2789. const OMPTargetParallelForSimdDirective *D) {
  2790. VisitOMPLoopDirective(D);
  2791. }
  2792. void EnqueueVisitor::VisitOMPTargetSimdDirective(
  2793. const OMPTargetSimdDirective *D) {
  2794. VisitOMPLoopDirective(D);
  2795. }
  2796. void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
  2797. const OMPTeamsDistributeDirective *D) {
  2798. VisitOMPLoopDirective(D);
  2799. }
  2800. void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
  2801. const OMPTeamsDistributeSimdDirective *D) {
  2802. VisitOMPLoopDirective(D);
  2803. }
  2804. void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
  2805. const OMPTeamsDistributeParallelForSimdDirective *D) {
  2806. VisitOMPLoopDirective(D);
  2807. }
  2808. void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
  2809. const OMPTeamsDistributeParallelForDirective *D) {
  2810. VisitOMPLoopDirective(D);
  2811. }
  2812. void EnqueueVisitor::VisitOMPTargetTeamsDirective(
  2813. const OMPTargetTeamsDirective *D) {
  2814. VisitOMPExecutableDirective(D);
  2815. }
  2816. void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
  2817. const OMPTargetTeamsDistributeDirective *D) {
  2818. VisitOMPLoopDirective(D);
  2819. }
  2820. void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
  2821. const OMPTargetTeamsDistributeParallelForDirective *D) {
  2822. VisitOMPLoopDirective(D);
  2823. }
  2824. void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
  2825. const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
  2826. VisitOMPLoopDirective(D);
  2827. }
  2828. void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
  2829. const OMPTargetTeamsDistributeSimdDirective *D) {
  2830. VisitOMPLoopDirective(D);
  2831. }
  2832. void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
  2833. EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
  2834. .Visit(S);
  2835. }
  2836. bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
  2837. if (RegionOfInterest.isValid()) {
  2838. SourceRange Range = getRawCursorExtent(C);
  2839. if (Range.isInvalid() || CompareRegionOfInterest(Range))
  2840. return false;
  2841. }
  2842. return true;
  2843. }
  2844. bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
  2845. while (!WL.empty()) {
  2846. // Dequeue the worklist item.
  2847. VisitorJob LI = WL.pop_back_val();
  2848. // Set the Parent field, then back to its old value once we're done.
  2849. SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
  2850. switch (LI.getKind()) {
  2851. case VisitorJob::DeclVisitKind: {
  2852. const Decl *D = cast<DeclVisit>(&LI)->get();
  2853. if (!D)
  2854. continue;
  2855. // For now, perform default visitation for Decls.
  2856. if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
  2857. cast<DeclVisit>(&LI)->isFirst())))
  2858. return true;
  2859. continue;
  2860. }
  2861. case VisitorJob::ExplicitTemplateArgsVisitKind: {
  2862. for (const TemplateArgumentLoc &Arg :
  2863. *cast<ExplicitTemplateArgsVisit>(&LI)) {
  2864. if (VisitTemplateArgumentLoc(Arg))
  2865. return true;
  2866. }
  2867. continue;
  2868. }
  2869. case VisitorJob::TypeLocVisitKind: {
  2870. // Perform default visitation for TypeLocs.
  2871. if (Visit(cast<TypeLocVisit>(&LI)->get()))
  2872. return true;
  2873. continue;
  2874. }
  2875. case VisitorJob::LabelRefVisitKind: {
  2876. const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
  2877. if (LabelStmt *stmt = LS->getStmt()) {
  2878. if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
  2879. TU))) {
  2880. return true;
  2881. }
  2882. }
  2883. continue;
  2884. }
  2885. case VisitorJob::NestedNameSpecifierLocVisitKind: {
  2886. NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
  2887. if (VisitNestedNameSpecifierLoc(V->get()))
  2888. return true;
  2889. continue;
  2890. }
  2891. case VisitorJob::DeclarationNameInfoVisitKind: {
  2892. if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get()))
  2893. return true;
  2894. continue;
  2895. }
  2896. case VisitorJob::MemberRefVisitKind: {
  2897. MemberRefVisit *V = cast<MemberRefVisit>(&LI);
  2898. if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
  2899. return true;
  2900. continue;
  2901. }
  2902. case VisitorJob::StmtVisitKind: {
  2903. const Stmt *S = cast<StmtVisit>(&LI)->get();
  2904. if (!S)
  2905. continue;
  2906. // Update the current cursor.
  2907. CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
  2908. if (!IsInRegionOfInterest(Cursor))
  2909. continue;
  2910. switch (Visitor(Cursor, Parent, ClientData)) {
  2911. case CXChildVisit_Break:
  2912. return true;
  2913. case CXChildVisit_Continue:
  2914. break;
  2915. case CXChildVisit_Recurse:
  2916. if (PostChildrenVisitor)
  2917. WL.push_back(PostChildrenVisit(nullptr, Cursor));
  2918. EnqueueWorkList(WL, S);
  2919. break;
  2920. }
  2921. continue;
  2922. }
  2923. case VisitorJob::MemberExprPartsKind: {
  2924. // Handle the other pieces in the MemberExpr besides the base.
  2925. const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
  2926. // Visit the nested-name-specifier
  2927. if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
  2928. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  2929. return true;
  2930. // Visit the declaration name.
  2931. if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
  2932. return true;
  2933. // Visit the explicitly-specified template arguments, if any.
  2934. if (M->hasExplicitTemplateArgs()) {
  2935. for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
  2936. *ArgEnd = Arg + M->getNumTemplateArgs();
  2937. Arg != ArgEnd; ++Arg) {
  2938. if (VisitTemplateArgumentLoc(*Arg))
  2939. return true;
  2940. }
  2941. }
  2942. continue;
  2943. }
  2944. case VisitorJob::DeclRefExprPartsKind: {
  2945. const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
  2946. // Visit nested-name-specifier, if present.
  2947. if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
  2948. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  2949. return true;
  2950. // Visit declaration name.
  2951. if (VisitDeclarationNameInfo(DR->getNameInfo()))
  2952. return true;
  2953. continue;
  2954. }
  2955. case VisitorJob::OverloadExprPartsKind: {
  2956. const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
  2957. // Visit the nested-name-specifier.
  2958. if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
  2959. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  2960. return true;
  2961. // Visit the declaration name.
  2962. if (VisitDeclarationNameInfo(O->getNameInfo()))
  2963. return true;
  2964. // Visit the overloaded declaration reference.
  2965. if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
  2966. return true;
  2967. continue;
  2968. }
  2969. case VisitorJob::SizeOfPackExprPartsKind: {
  2970. const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
  2971. NamedDecl *Pack = E->getPack();
  2972. if (isa<TemplateTypeParmDecl>(Pack)) {
  2973. if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
  2974. E->getPackLoc(), TU)))
  2975. return true;
  2976. continue;
  2977. }
  2978. if (isa<TemplateTemplateParmDecl>(Pack)) {
  2979. if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
  2980. E->getPackLoc(), TU)))
  2981. return true;
  2982. continue;
  2983. }
  2984. // Non-type template parameter packs and function parameter packs are
  2985. // treated like DeclRefExpr cursors.
  2986. continue;
  2987. }
  2988. case VisitorJob::LambdaExprPartsKind: {
  2989. // Visit non-init captures.
  2990. const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
  2991. for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
  2992. CEnd = E->explicit_capture_end();
  2993. C != CEnd; ++C) {
  2994. if (!C->capturesVariable())
  2995. continue;
  2996. // TODO: handle structured bindings here ?
  2997. if (!isa<VarDecl>(C->getCapturedVar()))
  2998. continue;
  2999. if (Visit(MakeCursorVariableRef(cast<VarDecl>(C->getCapturedVar()),
  3000. C->getLocation(), TU)))
  3001. return true;
  3002. }
  3003. // Visit init captures
  3004. for (auto InitExpr : E->capture_inits()) {
  3005. if (InitExpr && Visit(InitExpr))
  3006. return true;
  3007. }
  3008. TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
  3009. // Visit parameters and return type, if present.
  3010. if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
  3011. if (E->hasExplicitParameters()) {
  3012. // Visit parameters.
  3013. for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
  3014. if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
  3015. return true;
  3016. }
  3017. if (E->hasExplicitResultType()) {
  3018. // Visit result type.
  3019. if (Visit(Proto.getReturnLoc()))
  3020. return true;
  3021. }
  3022. }
  3023. break;
  3024. }
  3025. case VisitorJob::ConceptSpecializationExprVisitKind: {
  3026. const ConceptSpecializationExpr *E =
  3027. cast<ConceptSpecializationExprVisit>(&LI)->get();
  3028. if (NestedNameSpecifierLoc QualifierLoc =
  3029. E->getNestedNameSpecifierLoc()) {
  3030. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  3031. return true;
  3032. }
  3033. if (E->getNamedConcept() &&
  3034. Visit(MakeCursorTemplateRef(E->getNamedConcept(),
  3035. E->getConceptNameLoc(), TU)))
  3036. return true;
  3037. if (auto Args = E->getTemplateArgsAsWritten()) {
  3038. for (const auto &Arg : Args->arguments()) {
  3039. if (VisitTemplateArgumentLoc(Arg))
  3040. return true;
  3041. }
  3042. }
  3043. break;
  3044. }
  3045. case VisitorJob::RequiresExprVisitKind: {
  3046. const RequiresExpr *E = cast<RequiresExprVisit>(&LI)->get();
  3047. for (const concepts::Requirement *R : E->getRequirements())
  3048. VisitConceptRequirement(*R);
  3049. break;
  3050. }
  3051. case VisitorJob::PostChildrenVisitKind:
  3052. if (PostChildrenVisitor(Parent, ClientData))
  3053. return true;
  3054. break;
  3055. }
  3056. }
  3057. return false;
  3058. }
  3059. bool CursorVisitor::Visit(const Stmt *S) {
  3060. VisitorWorkList *WL = nullptr;
  3061. if (!WorkListFreeList.empty()) {
  3062. WL = WorkListFreeList.back();
  3063. WL->clear();
  3064. WorkListFreeList.pop_back();
  3065. } else {
  3066. WL = new VisitorWorkList();
  3067. WorkListCache.push_back(WL);
  3068. }
  3069. EnqueueWorkList(*WL, S);
  3070. bool result = RunVisitorWorkList(*WL);
  3071. WorkListFreeList.push_back(WL);
  3072. return result;
  3073. }
  3074. namespace {
  3075. typedef SmallVector<SourceRange, 4> RefNamePieces;
  3076. RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
  3077. const DeclarationNameInfo &NI, SourceRange QLoc,
  3078. const SourceRange *TemplateArgsLoc = nullptr) {
  3079. const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
  3080. const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
  3081. const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
  3082. const DeclarationName::NameKind Kind = NI.getName().getNameKind();
  3083. RefNamePieces Pieces;
  3084. if (WantQualifier && QLoc.isValid())
  3085. Pieces.push_back(QLoc);
  3086. if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
  3087. Pieces.push_back(NI.getLoc());
  3088. if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
  3089. Pieces.push_back(*TemplateArgsLoc);
  3090. if (Kind == DeclarationName::CXXOperatorName) {
  3091. Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc());
  3092. Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc());
  3093. }
  3094. if (WantSinglePiece) {
  3095. SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
  3096. Pieces.clear();
  3097. Pieces.push_back(R);
  3098. }
  3099. return Pieces;
  3100. }
  3101. } // namespace
  3102. //===----------------------------------------------------------------------===//
  3103. // Misc. API hooks.
  3104. //===----------------------------------------------------------------------===//
  3105. namespace {
  3106. struct RegisterFatalErrorHandler {
  3107. RegisterFatalErrorHandler() {
  3108. clang_install_aborting_llvm_fatal_error_handler();
  3109. }
  3110. };
  3111. } // namespace
  3112. static llvm::ManagedStatic<RegisterFatalErrorHandler>
  3113. RegisterFatalErrorHandlerOnce;
  3114. CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
  3115. int displayDiagnostics) {
  3116. // We use crash recovery to make some of our APIs more reliable, implicitly
  3117. // enable it.
  3118. if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
  3119. llvm::CrashRecoveryContext::Enable();
  3120. // Look through the managed static to trigger construction of the managed
  3121. // static which registers our fatal error handler. This ensures it is only
  3122. // registered once.
  3123. (void)*RegisterFatalErrorHandlerOnce;
  3124. // Initialize targets for clang module support.
  3125. llvm::InitializeAllTargets();
  3126. llvm::InitializeAllTargetMCs();
  3127. llvm::InitializeAllAsmPrinters();
  3128. llvm::InitializeAllAsmParsers();
  3129. CIndexer *CIdxr = new CIndexer();
  3130. if (excludeDeclarationsFromPCH)
  3131. CIdxr->setOnlyLocalDecls();
  3132. if (displayDiagnostics)
  3133. CIdxr->setDisplayDiagnostics();
  3134. if (getenv("LIBCLANG_BGPRIO_INDEX"))
  3135. CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
  3136. CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
  3137. if (getenv("LIBCLANG_BGPRIO_EDIT"))
  3138. CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
  3139. CXGlobalOpt_ThreadBackgroundPriorityForEditing);
  3140. return CIdxr;
  3141. }
  3142. void clang_disposeIndex(CXIndex CIdx) {
  3143. if (CIdx)
  3144. delete static_cast<CIndexer *>(CIdx);
  3145. }
  3146. void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
  3147. if (CIdx)
  3148. static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
  3149. }
  3150. unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
  3151. if (CIdx)
  3152. return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
  3153. return 0;
  3154. }
  3155. void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
  3156. const char *Path) {
  3157. if (CIdx)
  3158. static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
  3159. }
  3160. void clang_toggleCrashRecovery(unsigned isEnabled) {
  3161. if (isEnabled)
  3162. llvm::CrashRecoveryContext::Enable();
  3163. else
  3164. llvm::CrashRecoveryContext::Disable();
  3165. }
  3166. CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
  3167. const char *ast_filename) {
  3168. CXTranslationUnit TU;
  3169. enum CXErrorCode Result =
  3170. clang_createTranslationUnit2(CIdx, ast_filename, &TU);
  3171. (void)Result;
  3172. assert((TU && Result == CXError_Success) ||
  3173. (!TU && Result != CXError_Success));
  3174. return TU;
  3175. }
  3176. enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
  3177. const char *ast_filename,
  3178. CXTranslationUnit *out_TU) {
  3179. if (out_TU)
  3180. *out_TU = nullptr;
  3181. if (!CIdx || !ast_filename || !out_TU)
  3182. return CXError_InvalidArguments;
  3183. LOG_FUNC_SECTION { *Log << ast_filename; }
  3184. CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
  3185. FileSystemOptions FileSystemOpts;
  3186. IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
  3187. CompilerInstance::createDiagnostics(new DiagnosticOptions());
  3188. std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
  3189. ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
  3190. ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false,
  3191. CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All,
  3192. /*AllowASTWithCompilerErrors=*/true,
  3193. /*UserFilesAreVolatile=*/true);
  3194. *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
  3195. return *out_TU ? CXError_Success : CXError_Failure;
  3196. }
  3197. unsigned clang_defaultEditingTranslationUnitOptions() {
  3198. return CXTranslationUnit_PrecompiledPreamble |
  3199. CXTranslationUnit_CacheCompletionResults;
  3200. }
  3201. CXTranslationUnit clang_createTranslationUnitFromSourceFile(
  3202. CXIndex CIdx, const char *source_filename, int num_command_line_args,
  3203. const char *const *command_line_args, unsigned num_unsaved_files,
  3204. struct CXUnsavedFile *unsaved_files) {
  3205. unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
  3206. return clang_parseTranslationUnit(CIdx, source_filename, command_line_args,
  3207. num_command_line_args, unsaved_files,
  3208. num_unsaved_files, Options);
  3209. }
  3210. static CXErrorCode
  3211. clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
  3212. const char *const *command_line_args,
  3213. int num_command_line_args,
  3214. ArrayRef<CXUnsavedFile> unsaved_files,
  3215. unsigned options, CXTranslationUnit *out_TU) {
  3216. // Set up the initial return values.
  3217. if (out_TU)
  3218. *out_TU = nullptr;
  3219. // Check arguments.
  3220. if (!CIdx || !out_TU)
  3221. return CXError_InvalidArguments;
  3222. CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
  3223. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
  3224. setThreadBackgroundPriority();
  3225. bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
  3226. bool CreatePreambleOnFirstParse =
  3227. options & CXTranslationUnit_CreatePreambleOnFirstParse;
  3228. // FIXME: Add a flag for modules.
  3229. TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete |
  3230. CXTranslationUnit_SingleFileParse))
  3231. ? TU_Prefix
  3232. : TU_Complete;
  3233. bool CacheCodeCompletionResults =
  3234. options & CXTranslationUnit_CacheCompletionResults;
  3235. bool IncludeBriefCommentsInCodeCompletion =
  3236. options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
  3237. bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
  3238. bool ForSerialization = options & CXTranslationUnit_ForSerialization;
  3239. bool RetainExcludedCB =
  3240. options & CXTranslationUnit_RetainExcludedConditionalBlocks;
  3241. SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
  3242. if (options & CXTranslationUnit_SkipFunctionBodies) {
  3243. SkipFunctionBodies =
  3244. (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
  3245. ? SkipFunctionBodiesScope::Preamble
  3246. : SkipFunctionBodiesScope::PreambleAndMainFile;
  3247. }
  3248. // Configure the diagnostics.
  3249. std::unique_ptr<DiagnosticOptions> DiagOpts = CreateAndPopulateDiagOpts(
  3250. llvm::ArrayRef(command_line_args, num_command_line_args));
  3251. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  3252. CompilerInstance::createDiagnostics(DiagOpts.release()));
  3253. if (options & CXTranslationUnit_KeepGoing)
  3254. Diags->setFatalsAsError(true);
  3255. CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
  3256. if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
  3257. CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
  3258. // Recover resources if we crash before exiting this function.
  3259. llvm::CrashRecoveryContextCleanupRegistrar<
  3260. DiagnosticsEngine,
  3261. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  3262. DiagCleanup(Diags.get());
  3263. std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
  3264. new std::vector<ASTUnit::RemappedFile>());
  3265. // Recover resources if we crash before exiting this function.
  3266. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
  3267. RemappedCleanup(RemappedFiles.get());
  3268. for (auto &UF : unsaved_files) {
  3269. std::unique_ptr<llvm::MemoryBuffer> MB =
  3270. llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
  3271. RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
  3272. }
  3273. std::unique_ptr<std::vector<const char *>> Args(
  3274. new std::vector<const char *>());
  3275. // Recover resources if we crash before exiting this method.
  3276. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>>
  3277. ArgsCleanup(Args.get());
  3278. // Since the Clang C library is primarily used by batch tools dealing with
  3279. // (often very broken) source code, where spell-checking can have a
  3280. // significant negative impact on performance (particularly when
  3281. // precompiled headers are involved), we disable it by default.
  3282. // Only do this if we haven't found a spell-checking-related argument.
  3283. bool FoundSpellCheckingArgument = false;
  3284. for (int I = 0; I != num_command_line_args; ++I) {
  3285. if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
  3286. strcmp(command_line_args[I], "-fspell-checking") == 0) {
  3287. FoundSpellCheckingArgument = true;
  3288. break;
  3289. }
  3290. }
  3291. Args->insert(Args->end(), command_line_args,
  3292. command_line_args + num_command_line_args);
  3293. if (!FoundSpellCheckingArgument)
  3294. Args->insert(Args->begin() + 1, "-fno-spell-checking");
  3295. // The 'source_filename' argument is optional. If the caller does not
  3296. // specify it then it is assumed that the source file is specified
  3297. // in the actual argument list.
  3298. // Put the source file after command_line_args otherwise if '-x' flag is
  3299. // present it will be unused.
  3300. if (source_filename)
  3301. Args->push_back(source_filename);
  3302. // Do we need the detailed preprocessing record?
  3303. if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
  3304. Args->push_back("-Xclang");
  3305. Args->push_back("-detailed-preprocessing-record");
  3306. }
  3307. // Suppress any editor placeholder diagnostics.
  3308. Args->push_back("-fallow-editor-placeholders");
  3309. unsigned NumErrors = Diags->getClient()->getNumErrors();
  3310. std::unique_ptr<ASTUnit> ErrUnit;
  3311. // Unless the user specified that they want the preamble on the first parse
  3312. // set it up to be created on the first reparse. This makes the first parse
  3313. // faster, trading for a slower (first) reparse.
  3314. unsigned PrecompilePreambleAfterNParses =
  3315. !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
  3316. LibclangInvocationReporter InvocationReporter(
  3317. *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
  3318. options, llvm::ArrayRef(*Args), /*InvocationArgs=*/std::nullopt,
  3319. unsaved_files);
  3320. std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
  3321. Args->data(), Args->data() + Args->size(),
  3322. CXXIdx->getPCHContainerOperations(), Diags,
  3323. CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
  3324. CaptureDiagnostics, *RemappedFiles.get(),
  3325. /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
  3326. TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
  3327. /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
  3328. /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
  3329. CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
  3330. &ErrUnit));
  3331. // Early failures in LoadFromCommandLine may return with ErrUnit unset.
  3332. if (!Unit && !ErrUnit)
  3333. return CXError_ASTReadError;
  3334. if (NumErrors != Diags->getClient()->getNumErrors()) {
  3335. // Make sure to check that 'Unit' is non-NULL.
  3336. if (CXXIdx->getDisplayDiagnostics())
  3337. printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
  3338. }
  3339. if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
  3340. return CXError_ASTReadError;
  3341. *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
  3342. if (CXTranslationUnitImpl *TU = *out_TU) {
  3343. TU->ParsingOptions = options;
  3344. TU->Arguments.reserve(Args->size());
  3345. for (const char *Arg : *Args)
  3346. TU->Arguments.push_back(Arg);
  3347. return CXError_Success;
  3348. }
  3349. return CXError_Failure;
  3350. }
  3351. CXTranslationUnit
  3352. clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename,
  3353. const char *const *command_line_args,
  3354. int num_command_line_args,
  3355. struct CXUnsavedFile *unsaved_files,
  3356. unsigned num_unsaved_files, unsigned options) {
  3357. CXTranslationUnit TU;
  3358. enum CXErrorCode Result = clang_parseTranslationUnit2(
  3359. CIdx, source_filename, command_line_args, num_command_line_args,
  3360. unsaved_files, num_unsaved_files, options, &TU);
  3361. (void)Result;
  3362. assert((TU && Result == CXError_Success) ||
  3363. (!TU && Result != CXError_Success));
  3364. return TU;
  3365. }
  3366. enum CXErrorCode clang_parseTranslationUnit2(
  3367. CXIndex CIdx, const char *source_filename,
  3368. const char *const *command_line_args, int num_command_line_args,
  3369. struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
  3370. unsigned options, CXTranslationUnit *out_TU) {
  3371. noteBottomOfStack();
  3372. SmallVector<const char *, 4> Args;
  3373. Args.push_back("clang");
  3374. Args.append(command_line_args, command_line_args + num_command_line_args);
  3375. return clang_parseTranslationUnit2FullArgv(
  3376. CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
  3377. num_unsaved_files, options, out_TU);
  3378. }
  3379. enum CXErrorCode clang_parseTranslationUnit2FullArgv(
  3380. CXIndex CIdx, const char *source_filename,
  3381. const char *const *command_line_args, int num_command_line_args,
  3382. struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
  3383. unsigned options, CXTranslationUnit *out_TU) {
  3384. LOG_FUNC_SECTION {
  3385. *Log << source_filename << ": ";
  3386. for (int i = 0; i != num_command_line_args; ++i)
  3387. *Log << command_line_args[i] << " ";
  3388. }
  3389. if (num_unsaved_files && !unsaved_files)
  3390. return CXError_InvalidArguments;
  3391. CXErrorCode result = CXError_Failure;
  3392. auto ParseTranslationUnitImpl = [=, &result] {
  3393. noteBottomOfStack();
  3394. result = clang_parseTranslationUnit_Impl(
  3395. CIdx, source_filename, command_line_args, num_command_line_args,
  3396. llvm::ArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
  3397. };
  3398. llvm::CrashRecoveryContext CRC;
  3399. if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
  3400. fprintf(stderr, "libclang: crash detected during parsing: {\n");
  3401. fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
  3402. fprintf(stderr, " 'command_line_args' : [");
  3403. for (int i = 0; i != num_command_line_args; ++i) {
  3404. if (i)
  3405. fprintf(stderr, ", ");
  3406. fprintf(stderr, "'%s'", command_line_args[i]);
  3407. }
  3408. fprintf(stderr, "],\n");
  3409. fprintf(stderr, " 'unsaved_files' : [");
  3410. for (unsigned i = 0; i != num_unsaved_files; ++i) {
  3411. if (i)
  3412. fprintf(stderr, ", ");
  3413. fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
  3414. unsaved_files[i].Length);
  3415. }
  3416. fprintf(stderr, "],\n");
  3417. fprintf(stderr, " 'options' : %d,\n", options);
  3418. fprintf(stderr, "}\n");
  3419. return CXError_Crashed;
  3420. } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
  3421. if (CXTranslationUnit *TU = out_TU)
  3422. PrintLibclangResourceUsage(*TU);
  3423. }
  3424. return result;
  3425. }
  3426. CXString clang_Type_getObjCEncoding(CXType CT) {
  3427. CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
  3428. ASTContext &Ctx = getASTUnit(tu)->getASTContext();
  3429. std::string encoding;
  3430. Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding);
  3431. return cxstring::createDup(encoding);
  3432. }
  3433. static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
  3434. if (C.kind == CXCursor_MacroDefinition) {
  3435. if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
  3436. return MDR->getName();
  3437. } else if (C.kind == CXCursor_MacroExpansion) {
  3438. MacroExpansionCursor ME = getCursorMacroExpansion(C);
  3439. return ME.getName();
  3440. }
  3441. return nullptr;
  3442. }
  3443. unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
  3444. const IdentifierInfo *II = getMacroIdentifier(C);
  3445. if (!II) {
  3446. return false;
  3447. }
  3448. ASTUnit *ASTU = getCursorASTUnit(C);
  3449. Preprocessor &PP = ASTU->getPreprocessor();
  3450. if (const MacroInfo *MI = PP.getMacroInfo(II))
  3451. return MI->isFunctionLike();
  3452. return false;
  3453. }
  3454. unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
  3455. const IdentifierInfo *II = getMacroIdentifier(C);
  3456. if (!II) {
  3457. return false;
  3458. }
  3459. ASTUnit *ASTU = getCursorASTUnit(C);
  3460. Preprocessor &PP = ASTU->getPreprocessor();
  3461. if (const MacroInfo *MI = PP.getMacroInfo(II))
  3462. return MI->isBuiltinMacro();
  3463. return false;
  3464. }
  3465. unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
  3466. const Decl *D = getCursorDecl(C);
  3467. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  3468. if (!FD) {
  3469. return false;
  3470. }
  3471. return FD->isInlined();
  3472. }
  3473. static StringLiteral *getCFSTR_value(CallExpr *callExpr) {
  3474. if (callExpr->getNumArgs() != 1) {
  3475. return nullptr;
  3476. }
  3477. StringLiteral *S = nullptr;
  3478. auto *arg = callExpr->getArg(0);
  3479. if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
  3480. ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
  3481. auto *subExpr = I->getSubExprAsWritten();
  3482. if (subExpr->getStmtClass() != Stmt::StringLiteralClass) {
  3483. return nullptr;
  3484. }
  3485. S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
  3486. } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
  3487. S = static_cast<StringLiteral *>(callExpr->getArg(0));
  3488. } else {
  3489. return nullptr;
  3490. }
  3491. return S;
  3492. }
  3493. struct ExprEvalResult {
  3494. CXEvalResultKind EvalType;
  3495. union {
  3496. unsigned long long unsignedVal;
  3497. long long intVal;
  3498. double floatVal;
  3499. char *stringVal;
  3500. } EvalData;
  3501. bool IsUnsignedInt;
  3502. ~ExprEvalResult() {
  3503. if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
  3504. EvalType != CXEval_Int) {
  3505. delete[] EvalData.stringVal;
  3506. }
  3507. }
  3508. };
  3509. void clang_EvalResult_dispose(CXEvalResult E) {
  3510. delete static_cast<ExprEvalResult *>(E);
  3511. }
  3512. CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
  3513. if (!E) {
  3514. return CXEval_UnExposed;
  3515. }
  3516. return ((ExprEvalResult *)E)->EvalType;
  3517. }
  3518. int clang_EvalResult_getAsInt(CXEvalResult E) {
  3519. return clang_EvalResult_getAsLongLong(E);
  3520. }
  3521. long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
  3522. if (!E) {
  3523. return 0;
  3524. }
  3525. ExprEvalResult *Result = (ExprEvalResult *)E;
  3526. if (Result->IsUnsignedInt)
  3527. return Result->EvalData.unsignedVal;
  3528. return Result->EvalData.intVal;
  3529. }
  3530. unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
  3531. return ((ExprEvalResult *)E)->IsUnsignedInt;
  3532. }
  3533. unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
  3534. if (!E) {
  3535. return 0;
  3536. }
  3537. ExprEvalResult *Result = (ExprEvalResult *)E;
  3538. if (Result->IsUnsignedInt)
  3539. return Result->EvalData.unsignedVal;
  3540. return Result->EvalData.intVal;
  3541. }
  3542. double clang_EvalResult_getAsDouble(CXEvalResult E) {
  3543. if (!E) {
  3544. return 0;
  3545. }
  3546. return ((ExprEvalResult *)E)->EvalData.floatVal;
  3547. }
  3548. const char *clang_EvalResult_getAsStr(CXEvalResult E) {
  3549. if (!E) {
  3550. return nullptr;
  3551. }
  3552. return ((ExprEvalResult *)E)->EvalData.stringVal;
  3553. }
  3554. static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
  3555. Expr::EvalResult ER;
  3556. ASTContext &ctx = getCursorContext(C);
  3557. if (!expr)
  3558. return nullptr;
  3559. expr = expr->IgnoreParens();
  3560. if (expr->isValueDependent())
  3561. return nullptr;
  3562. if (!expr->EvaluateAsRValue(ER, ctx))
  3563. return nullptr;
  3564. QualType rettype;
  3565. CallExpr *callExpr;
  3566. auto result = std::make_unique<ExprEvalResult>();
  3567. result->EvalType = CXEval_UnExposed;
  3568. result->IsUnsignedInt = false;
  3569. if (ER.Val.isInt()) {
  3570. result->EvalType = CXEval_Int;
  3571. auto &val = ER.Val.getInt();
  3572. if (val.isUnsigned()) {
  3573. result->IsUnsignedInt = true;
  3574. result->EvalData.unsignedVal = val.getZExtValue();
  3575. } else {
  3576. result->EvalData.intVal = val.getExtValue();
  3577. }
  3578. return result.release();
  3579. }
  3580. if (ER.Val.isFloat()) {
  3581. llvm::SmallVector<char, 100> Buffer;
  3582. ER.Val.getFloat().toString(Buffer);
  3583. std::string floatStr(Buffer.data(), Buffer.size());
  3584. result->EvalType = CXEval_Float;
  3585. bool ignored;
  3586. llvm::APFloat apFloat = ER.Val.getFloat();
  3587. apFloat.convert(llvm::APFloat::IEEEdouble(),
  3588. llvm::APFloat::rmNearestTiesToEven, &ignored);
  3589. result->EvalData.floatVal = apFloat.convertToDouble();
  3590. return result.release();
  3591. }
  3592. if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
  3593. const auto *I = cast<ImplicitCastExpr>(expr);
  3594. auto *subExpr = I->getSubExprAsWritten();
  3595. if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
  3596. subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
  3597. const StringLiteral *StrE = nullptr;
  3598. const ObjCStringLiteral *ObjCExpr;
  3599. ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
  3600. if (ObjCExpr) {
  3601. StrE = ObjCExpr->getString();
  3602. result->EvalType = CXEval_ObjCStrLiteral;
  3603. } else {
  3604. StrE = cast<StringLiteral>(I->getSubExprAsWritten());
  3605. result->EvalType = CXEval_StrLiteral;
  3606. }
  3607. std::string strRef(StrE->getString().str());
  3608. result->EvalData.stringVal = new char[strRef.size() + 1];
  3609. strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
  3610. strRef.size());
  3611. result->EvalData.stringVal[strRef.size()] = '\0';
  3612. return result.release();
  3613. }
  3614. } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
  3615. expr->getStmtClass() == Stmt::StringLiteralClass) {
  3616. const StringLiteral *StrE = nullptr;
  3617. const ObjCStringLiteral *ObjCExpr;
  3618. ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
  3619. if (ObjCExpr) {
  3620. StrE = ObjCExpr->getString();
  3621. result->EvalType = CXEval_ObjCStrLiteral;
  3622. } else {
  3623. StrE = cast<StringLiteral>(expr);
  3624. result->EvalType = CXEval_StrLiteral;
  3625. }
  3626. std::string strRef(StrE->getString().str());
  3627. result->EvalData.stringVal = new char[strRef.size() + 1];
  3628. strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
  3629. result->EvalData.stringVal[strRef.size()] = '\0';
  3630. return result.release();
  3631. }
  3632. if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
  3633. CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
  3634. rettype = CC->getType();
  3635. if (rettype.getAsString() == "CFStringRef" &&
  3636. CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
  3637. callExpr = static_cast<CallExpr *>(CC->getSubExpr());
  3638. StringLiteral *S = getCFSTR_value(callExpr);
  3639. if (S) {
  3640. std::string strLiteral(S->getString().str());
  3641. result->EvalType = CXEval_CFStr;
  3642. result->EvalData.stringVal = new char[strLiteral.size() + 1];
  3643. strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
  3644. strLiteral.size());
  3645. result->EvalData.stringVal[strLiteral.size()] = '\0';
  3646. return result.release();
  3647. }
  3648. }
  3649. } else if (expr->getStmtClass() == Stmt::CallExprClass) {
  3650. callExpr = static_cast<CallExpr *>(expr);
  3651. rettype = callExpr->getCallReturnType(ctx);
  3652. if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
  3653. return nullptr;
  3654. if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
  3655. if (callExpr->getNumArgs() == 1 &&
  3656. !callExpr->getArg(0)->getType()->isIntegralType(ctx))
  3657. return nullptr;
  3658. } else if (rettype.getAsString() == "CFStringRef") {
  3659. StringLiteral *S = getCFSTR_value(callExpr);
  3660. if (S) {
  3661. std::string strLiteral(S->getString().str());
  3662. result->EvalType = CXEval_CFStr;
  3663. result->EvalData.stringVal = new char[strLiteral.size() + 1];
  3664. strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
  3665. strLiteral.size());
  3666. result->EvalData.stringVal[strLiteral.size()] = '\0';
  3667. return result.release();
  3668. }
  3669. }
  3670. } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
  3671. DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
  3672. ValueDecl *V = D->getDecl();
  3673. if (V->getKind() == Decl::Function) {
  3674. std::string strName = V->getNameAsString();
  3675. result->EvalType = CXEval_Other;
  3676. result->EvalData.stringVal = new char[strName.size() + 1];
  3677. strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
  3678. result->EvalData.stringVal[strName.size()] = '\0';
  3679. return result.release();
  3680. }
  3681. }
  3682. return nullptr;
  3683. }
  3684. static const Expr *evaluateDeclExpr(const Decl *D) {
  3685. if (!D)
  3686. return nullptr;
  3687. if (auto *Var = dyn_cast<VarDecl>(D))
  3688. return Var->getInit();
  3689. else if (auto *Field = dyn_cast<FieldDecl>(D))
  3690. return Field->getInClassInitializer();
  3691. return nullptr;
  3692. }
  3693. static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
  3694. assert(CS && "invalid compound statement");
  3695. for (auto *bodyIterator : CS->body()) {
  3696. if (const auto *E = dyn_cast<Expr>(bodyIterator))
  3697. return E;
  3698. }
  3699. return nullptr;
  3700. }
  3701. CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
  3702. const Expr *E = nullptr;
  3703. if (clang_getCursorKind(C) == CXCursor_CompoundStmt)
  3704. E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)));
  3705. else if (clang_isDeclaration(C.kind))
  3706. E = evaluateDeclExpr(getCursorDecl(C));
  3707. else if (clang_isExpression(C.kind))
  3708. E = getCursorExpr(C);
  3709. if (E)
  3710. return const_cast<CXEvalResult>(
  3711. reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
  3712. return nullptr;
  3713. }
  3714. unsigned clang_Cursor_hasAttrs(CXCursor C) {
  3715. const Decl *D = getCursorDecl(C);
  3716. if (!D) {
  3717. return 0;
  3718. }
  3719. if (D->hasAttrs()) {
  3720. return 1;
  3721. }
  3722. return 0;
  3723. }
  3724. unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
  3725. return CXSaveTranslationUnit_None;
  3726. }
  3727. static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
  3728. const char *FileName,
  3729. unsigned options) {
  3730. CIndexer *CXXIdx = TU->CIdx;
  3731. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
  3732. setThreadBackgroundPriority();
  3733. bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
  3734. return hadError ? CXSaveError_Unknown : CXSaveError_None;
  3735. }
  3736. int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
  3737. unsigned options) {
  3738. LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; }
  3739. if (isNotUsableTU(TU)) {
  3740. LOG_BAD_TU(TU);
  3741. return CXSaveError_InvalidTU;
  3742. }
  3743. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3744. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  3745. if (!CXXUnit->hasSema())
  3746. return CXSaveError_InvalidTU;
  3747. CXSaveError result;
  3748. auto SaveTranslationUnitImpl = [=, &result]() {
  3749. result = clang_saveTranslationUnit_Impl(TU, FileName, options);
  3750. };
  3751. if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
  3752. SaveTranslationUnitImpl();
  3753. if (getenv("LIBCLANG_RESOURCE_USAGE"))
  3754. PrintLibclangResourceUsage(TU);
  3755. return result;
  3756. }
  3757. // We have an AST that has invalid nodes due to compiler errors.
  3758. // Use a crash recovery thread for protection.
  3759. llvm::CrashRecoveryContext CRC;
  3760. if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
  3761. fprintf(stderr, "libclang: crash detected during AST saving: {\n");
  3762. fprintf(stderr, " 'filename' : '%s'\n", FileName);
  3763. fprintf(stderr, " 'options' : %d,\n", options);
  3764. fprintf(stderr, "}\n");
  3765. return CXSaveError_Unknown;
  3766. } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
  3767. PrintLibclangResourceUsage(TU);
  3768. }
  3769. return result;
  3770. }
  3771. void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
  3772. if (CTUnit) {
  3773. // If the translation unit has been marked as unsafe to free, just discard
  3774. // it.
  3775. ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
  3776. if (Unit && Unit->isUnsafeToFree())
  3777. return;
  3778. delete cxtu::getASTUnit(CTUnit);
  3779. delete CTUnit->StringPool;
  3780. delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
  3781. disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
  3782. delete CTUnit->CommentToXML;
  3783. delete CTUnit;
  3784. }
  3785. }
  3786. unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
  3787. if (CTUnit) {
  3788. ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
  3789. if (Unit && Unit->isUnsafeToFree())
  3790. return false;
  3791. Unit->ResetForParse();
  3792. return true;
  3793. }
  3794. return false;
  3795. }
  3796. unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
  3797. return CXReparse_None;
  3798. }
  3799. static CXErrorCode
  3800. clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
  3801. ArrayRef<CXUnsavedFile> unsaved_files,
  3802. unsigned options) {
  3803. // Check arguments.
  3804. if (isNotUsableTU(TU)) {
  3805. LOG_BAD_TU(TU);
  3806. return CXError_InvalidArguments;
  3807. }
  3808. // Reset the associated diagnostics.
  3809. delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics);
  3810. TU->Diagnostics = nullptr;
  3811. CIndexer *CXXIdx = TU->CIdx;
  3812. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
  3813. setThreadBackgroundPriority();
  3814. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3815. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  3816. std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
  3817. new std::vector<ASTUnit::RemappedFile>());
  3818. // Recover resources if we crash before exiting this function.
  3819. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
  3820. RemappedCleanup(RemappedFiles.get());
  3821. for (auto &UF : unsaved_files) {
  3822. std::unique_ptr<llvm::MemoryBuffer> MB =
  3823. llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
  3824. RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
  3825. }
  3826. if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
  3827. *RemappedFiles.get()))
  3828. return CXError_Success;
  3829. if (isASTReadError(CXXUnit))
  3830. return CXError_ASTReadError;
  3831. return CXError_Failure;
  3832. }
  3833. int clang_reparseTranslationUnit(CXTranslationUnit TU,
  3834. unsigned num_unsaved_files,
  3835. struct CXUnsavedFile *unsaved_files,
  3836. unsigned options) {
  3837. LOG_FUNC_SECTION { *Log << TU; }
  3838. if (num_unsaved_files && !unsaved_files)
  3839. return CXError_InvalidArguments;
  3840. CXErrorCode result;
  3841. auto ReparseTranslationUnitImpl = [=, &result]() {
  3842. result = clang_reparseTranslationUnit_Impl(
  3843. TU, llvm::ArrayRef(unsaved_files, num_unsaved_files), options);
  3844. };
  3845. llvm::CrashRecoveryContext CRC;
  3846. if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
  3847. fprintf(stderr, "libclang: crash detected during reparsing\n");
  3848. cxtu::getASTUnit(TU)->setUnsafeToFree(true);
  3849. return CXError_Crashed;
  3850. } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
  3851. PrintLibclangResourceUsage(TU);
  3852. return result;
  3853. }
  3854. CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
  3855. if (isNotUsableTU(CTUnit)) {
  3856. LOG_BAD_TU(CTUnit);
  3857. return cxstring::createEmpty();
  3858. }
  3859. ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
  3860. return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
  3861. }
  3862. CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
  3863. if (isNotUsableTU(TU)) {
  3864. LOG_BAD_TU(TU);
  3865. return clang_getNullCursor();
  3866. }
  3867. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3868. return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
  3869. }
  3870. CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
  3871. if (isNotUsableTU(CTUnit)) {
  3872. LOG_BAD_TU(CTUnit);
  3873. return nullptr;
  3874. }
  3875. CXTargetInfoImpl *impl = new CXTargetInfoImpl();
  3876. impl->TranslationUnit = CTUnit;
  3877. return impl;
  3878. }
  3879. CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
  3880. if (!TargetInfo)
  3881. return cxstring::createEmpty();
  3882. CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
  3883. assert(!isNotUsableTU(CTUnit) &&
  3884. "Unexpected unusable translation unit in TargetInfo");
  3885. ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
  3886. std::string Triple =
  3887. CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
  3888. return cxstring::createDup(Triple);
  3889. }
  3890. int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
  3891. if (!TargetInfo)
  3892. return -1;
  3893. CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
  3894. assert(!isNotUsableTU(CTUnit) &&
  3895. "Unexpected unusable translation unit in TargetInfo");
  3896. ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
  3897. return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
  3898. }
  3899. void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
  3900. if (!TargetInfo)
  3901. return;
  3902. delete TargetInfo;
  3903. }
  3904. //===----------------------------------------------------------------------===//
  3905. // CXFile Operations.
  3906. //===----------------------------------------------------------------------===//
  3907. CXString clang_getFileName(CXFile SFile) {
  3908. if (!SFile)
  3909. return cxstring::createNull();
  3910. FileEntry *FEnt = static_cast<FileEntry *>(SFile);
  3911. return cxstring::createRef(FEnt->getName());
  3912. }
  3913. time_t clang_getFileTime(CXFile SFile) {
  3914. if (!SFile)
  3915. return 0;
  3916. FileEntry *FEnt = static_cast<FileEntry *>(SFile);
  3917. return FEnt->getModificationTime();
  3918. }
  3919. CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
  3920. if (isNotUsableTU(TU)) {
  3921. LOG_BAD_TU(TU);
  3922. return nullptr;
  3923. }
  3924. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3925. FileManager &FMgr = CXXUnit->getFileManager();
  3926. auto File = FMgr.getFile(file_name);
  3927. if (!File)
  3928. return nullptr;
  3929. return const_cast<FileEntry *>(*File);
  3930. }
  3931. const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
  3932. size_t *size) {
  3933. if (isNotUsableTU(TU)) {
  3934. LOG_BAD_TU(TU);
  3935. return nullptr;
  3936. }
  3937. const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
  3938. FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
  3939. std::optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid);
  3940. if (!buf) {
  3941. if (size)
  3942. *size = 0;
  3943. return nullptr;
  3944. }
  3945. if (size)
  3946. *size = buf->getBufferSize();
  3947. return buf->getBufferStart();
  3948. }
  3949. unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
  3950. if (isNotUsableTU(TU)) {
  3951. LOG_BAD_TU(TU);
  3952. return 0;
  3953. }
  3954. if (!file)
  3955. return 0;
  3956. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3957. FileEntry *FEnt = static_cast<FileEntry *>(file);
  3958. return CXXUnit->getPreprocessor()
  3959. .getHeaderSearchInfo()
  3960. .isFileMultipleIncludeGuarded(FEnt);
  3961. }
  3962. int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
  3963. if (!file || !outID)
  3964. return 1;
  3965. FileEntry *FEnt = static_cast<FileEntry *>(file);
  3966. const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
  3967. outID->data[0] = ID.getDevice();
  3968. outID->data[1] = ID.getFile();
  3969. outID->data[2] = FEnt->getModificationTime();
  3970. return 0;
  3971. }
  3972. int clang_File_isEqual(CXFile file1, CXFile file2) {
  3973. if (file1 == file2)
  3974. return true;
  3975. if (!file1 || !file2)
  3976. return false;
  3977. FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
  3978. FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
  3979. return FEnt1->getUniqueID() == FEnt2->getUniqueID();
  3980. }
  3981. CXString clang_File_tryGetRealPathName(CXFile SFile) {
  3982. if (!SFile)
  3983. return cxstring::createNull();
  3984. FileEntry *FEnt = static_cast<FileEntry *>(SFile);
  3985. return cxstring::createRef(FEnt->tryGetRealPathName());
  3986. }
  3987. //===----------------------------------------------------------------------===//
  3988. // CXCursor Operations.
  3989. //===----------------------------------------------------------------------===//
  3990. static const Decl *getDeclFromExpr(const Stmt *E) {
  3991. if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
  3992. return getDeclFromExpr(CE->getSubExpr());
  3993. if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
  3994. return RefExpr->getDecl();
  3995. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  3996. return ME->getMemberDecl();
  3997. if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
  3998. return RE->getDecl();
  3999. if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
  4000. if (PRE->isExplicitProperty())
  4001. return PRE->getExplicitProperty();
  4002. // It could be messaging both getter and setter as in:
  4003. // ++myobj.myprop;
  4004. // in which case prefer to associate the setter since it is less obvious
  4005. // from inspecting the source that the setter is going to get called.
  4006. if (PRE->isMessagingSetter())
  4007. return PRE->getImplicitPropertySetter();
  4008. return PRE->getImplicitPropertyGetter();
  4009. }
  4010. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  4011. return getDeclFromExpr(POE->getSyntacticForm());
  4012. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
  4013. if (Expr *Src = OVE->getSourceExpr())
  4014. return getDeclFromExpr(Src);
  4015. if (const CallExpr *CE = dyn_cast<CallExpr>(E))
  4016. return getDeclFromExpr(CE->getCallee());
  4017. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
  4018. if (!CE->isElidable())
  4019. return CE->getConstructor();
  4020. if (const CXXInheritedCtorInitExpr *CE =
  4021. dyn_cast<CXXInheritedCtorInitExpr>(E))
  4022. return CE->getConstructor();
  4023. if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
  4024. return OME->getMethodDecl();
  4025. if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
  4026. return PE->getProtocol();
  4027. if (const SubstNonTypeTemplateParmPackExpr *NTTP =
  4028. dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
  4029. return NTTP->getParameterPack();
  4030. if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
  4031. if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
  4032. isa<ParmVarDecl>(SizeOfPack->getPack()))
  4033. return SizeOfPack->getPack();
  4034. return nullptr;
  4035. }
  4036. static SourceLocation getLocationFromExpr(const Expr *E) {
  4037. if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
  4038. return getLocationFromExpr(CE->getSubExpr());
  4039. if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
  4040. return /*FIXME:*/ Msg->getLeftLoc();
  4041. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4042. return DRE->getLocation();
  4043. if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
  4044. return Member->getMemberLoc();
  4045. if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
  4046. return Ivar->getLocation();
  4047. if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
  4048. return SizeOfPack->getPackLoc();
  4049. if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
  4050. return PropRef->getLocation();
  4051. return E->getBeginLoc();
  4052. }
  4053. extern "C" {
  4054. unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor,
  4055. CXClientData client_data) {
  4056. CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
  4057. /*VisitPreprocessorLast=*/false);
  4058. return CursorVis.VisitChildren(parent);
  4059. }
  4060. #ifndef __has_feature
  4061. #define __has_feature(x) 0
  4062. #endif
  4063. #if __has_feature(blocks)
  4064. typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor,
  4065. CXCursor parent);
  4066. static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
  4067. CXClientData client_data) {
  4068. CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
  4069. return block(cursor, parent);
  4070. }
  4071. #else
  4072. // If we are compiled with a compiler that doesn't have native blocks support,
  4073. // define and call the block manually, so the
  4074. typedef struct _CXChildVisitResult {
  4075. void *isa;
  4076. int flags;
  4077. int reserved;
  4078. enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor,
  4079. CXCursor);
  4080. } * CXCursorVisitorBlock;
  4081. static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
  4082. CXClientData client_data) {
  4083. CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
  4084. return block->invoke(block, cursor, parent);
  4085. }
  4086. #endif
  4087. unsigned clang_visitChildrenWithBlock(CXCursor parent,
  4088. CXCursorVisitorBlock block) {
  4089. return clang_visitChildren(parent, visitWithBlock, block);
  4090. }
  4091. static CXString getDeclSpelling(const Decl *D) {
  4092. if (!D)
  4093. return cxstring::createEmpty();
  4094. const NamedDecl *ND = dyn_cast<NamedDecl>(D);
  4095. if (!ND) {
  4096. if (const ObjCPropertyImplDecl *PropImpl =
  4097. dyn_cast<ObjCPropertyImplDecl>(D))
  4098. if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
  4099. return cxstring::createDup(Property->getIdentifier()->getName());
  4100. if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
  4101. if (Module *Mod = ImportD->getImportedModule())
  4102. return cxstring::createDup(Mod->getFullModuleName());
  4103. return cxstring::createEmpty();
  4104. }
  4105. if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
  4106. return cxstring::createDup(OMD->getSelector().getAsString());
  4107. if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
  4108. // No, this isn't the same as the code below. getIdentifier() is non-virtual
  4109. // and returns different names. NamedDecl returns the class name and
  4110. // ObjCCategoryImplDecl returns the category name.
  4111. return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
  4112. if (isa<UsingDirectiveDecl>(D))
  4113. return cxstring::createEmpty();
  4114. SmallString<1024> S;
  4115. llvm::raw_svector_ostream os(S);
  4116. ND->printName(os);
  4117. return cxstring::createDup(os.str());
  4118. }
  4119. CXString clang_getCursorSpelling(CXCursor C) {
  4120. if (clang_isTranslationUnit(C.kind))
  4121. return clang_getTranslationUnitSpelling(getCursorTU(C));
  4122. if (clang_isReference(C.kind)) {
  4123. switch (C.kind) {
  4124. case CXCursor_ObjCSuperClassRef: {
  4125. const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
  4126. return cxstring::createRef(Super->getIdentifier()->getNameStart());
  4127. }
  4128. case CXCursor_ObjCClassRef: {
  4129. const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
  4130. return cxstring::createRef(Class->getIdentifier()->getNameStart());
  4131. }
  4132. case CXCursor_ObjCProtocolRef: {
  4133. const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
  4134. assert(OID && "getCursorSpelling(): Missing protocol decl");
  4135. return cxstring::createRef(OID->getIdentifier()->getNameStart());
  4136. }
  4137. case CXCursor_CXXBaseSpecifier: {
  4138. const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
  4139. return cxstring::createDup(B->getType().getAsString());
  4140. }
  4141. case CXCursor_TypeRef: {
  4142. const TypeDecl *Type = getCursorTypeRef(C).first;
  4143. assert(Type && "Missing type decl");
  4144. return cxstring::createDup(
  4145. getCursorContext(C).getTypeDeclType(Type).getAsString());
  4146. }
  4147. case CXCursor_TemplateRef: {
  4148. const TemplateDecl *Template = getCursorTemplateRef(C).first;
  4149. assert(Template && "Missing template decl");
  4150. return cxstring::createDup(Template->getNameAsString());
  4151. }
  4152. case CXCursor_NamespaceRef: {
  4153. const NamedDecl *NS = getCursorNamespaceRef(C).first;
  4154. assert(NS && "Missing namespace decl");
  4155. return cxstring::createDup(NS->getNameAsString());
  4156. }
  4157. case CXCursor_MemberRef: {
  4158. const FieldDecl *Field = getCursorMemberRef(C).first;
  4159. assert(Field && "Missing member decl");
  4160. return cxstring::createDup(Field->getNameAsString());
  4161. }
  4162. case CXCursor_LabelRef: {
  4163. const LabelStmt *Label = getCursorLabelRef(C).first;
  4164. assert(Label && "Missing label");
  4165. return cxstring::createRef(Label->getName());
  4166. }
  4167. case CXCursor_OverloadedDeclRef: {
  4168. OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
  4169. if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
  4170. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  4171. return cxstring::createDup(ND->getNameAsString());
  4172. return cxstring::createEmpty();
  4173. }
  4174. if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
  4175. return cxstring::createDup(E->getName().getAsString());
  4176. OverloadedTemplateStorage *Ovl =
  4177. Storage.get<OverloadedTemplateStorage *>();
  4178. if (Ovl->size() == 0)
  4179. return cxstring::createEmpty();
  4180. return cxstring::createDup((*Ovl->begin())->getNameAsString());
  4181. }
  4182. case CXCursor_VariableRef: {
  4183. const VarDecl *Var = getCursorVariableRef(C).first;
  4184. assert(Var && "Missing variable decl");
  4185. return cxstring::createDup(Var->getNameAsString());
  4186. }
  4187. default:
  4188. return cxstring::createRef("<not implemented>");
  4189. }
  4190. }
  4191. if (clang_isExpression(C.kind)) {
  4192. const Expr *E = getCursorExpr(C);
  4193. if (C.kind == CXCursor_ObjCStringLiteral ||
  4194. C.kind == CXCursor_StringLiteral) {
  4195. const StringLiteral *SLit;
  4196. if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
  4197. SLit = OSL->getString();
  4198. } else {
  4199. SLit = cast<StringLiteral>(E);
  4200. }
  4201. SmallString<256> Buf;
  4202. llvm::raw_svector_ostream OS(Buf);
  4203. SLit->outputString(OS);
  4204. return cxstring::createDup(OS.str());
  4205. }
  4206. const Decl *D = getDeclFromExpr(getCursorExpr(C));
  4207. if (D)
  4208. return getDeclSpelling(D);
  4209. return cxstring::createEmpty();
  4210. }
  4211. if (clang_isStatement(C.kind)) {
  4212. const Stmt *S = getCursorStmt(C);
  4213. if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
  4214. return cxstring::createRef(Label->getName());
  4215. return cxstring::createEmpty();
  4216. }
  4217. if (C.kind == CXCursor_MacroExpansion)
  4218. return cxstring::createRef(
  4219. getCursorMacroExpansion(C).getName()->getNameStart());
  4220. if (C.kind == CXCursor_MacroDefinition)
  4221. return cxstring::createRef(
  4222. getCursorMacroDefinition(C)->getName()->getNameStart());
  4223. if (C.kind == CXCursor_InclusionDirective)
  4224. return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
  4225. if (clang_isDeclaration(C.kind))
  4226. return getDeclSpelling(getCursorDecl(C));
  4227. if (C.kind == CXCursor_AnnotateAttr) {
  4228. const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
  4229. return cxstring::createDup(AA->getAnnotation());
  4230. }
  4231. if (C.kind == CXCursor_AsmLabelAttr) {
  4232. const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
  4233. return cxstring::createDup(AA->getLabel());
  4234. }
  4235. if (C.kind == CXCursor_PackedAttr) {
  4236. return cxstring::createRef("packed");
  4237. }
  4238. if (C.kind == CXCursor_VisibilityAttr) {
  4239. const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
  4240. switch (AA->getVisibility()) {
  4241. case VisibilityAttr::VisibilityType::Default:
  4242. return cxstring::createRef("default");
  4243. case VisibilityAttr::VisibilityType::Hidden:
  4244. return cxstring::createRef("hidden");
  4245. case VisibilityAttr::VisibilityType::Protected:
  4246. return cxstring::createRef("protected");
  4247. }
  4248. llvm_unreachable("unknown visibility type");
  4249. }
  4250. return cxstring::createEmpty();
  4251. }
  4252. CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex,
  4253. unsigned options) {
  4254. if (clang_Cursor_isNull(C))
  4255. return clang_getNullRange();
  4256. ASTContext &Ctx = getCursorContext(C);
  4257. if (clang_isStatement(C.kind)) {
  4258. const Stmt *S = getCursorStmt(C);
  4259. if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
  4260. if (pieceIndex > 0)
  4261. return clang_getNullRange();
  4262. return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
  4263. }
  4264. return clang_getNullRange();
  4265. }
  4266. if (C.kind == CXCursor_ObjCMessageExpr) {
  4267. if (const ObjCMessageExpr *ME =
  4268. dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
  4269. if (pieceIndex >= ME->getNumSelectorLocs())
  4270. return clang_getNullRange();
  4271. return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
  4272. }
  4273. }
  4274. if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
  4275. C.kind == CXCursor_ObjCClassMethodDecl) {
  4276. if (const ObjCMethodDecl *MD =
  4277. dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
  4278. if (pieceIndex >= MD->getNumSelectorLocs())
  4279. return clang_getNullRange();
  4280. return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
  4281. }
  4282. }
  4283. if (C.kind == CXCursor_ObjCCategoryDecl ||
  4284. C.kind == CXCursor_ObjCCategoryImplDecl) {
  4285. if (pieceIndex > 0)
  4286. return clang_getNullRange();
  4287. if (const ObjCCategoryDecl *CD =
  4288. dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
  4289. return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
  4290. if (const ObjCCategoryImplDecl *CID =
  4291. dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
  4292. return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
  4293. }
  4294. if (C.kind == CXCursor_ModuleImportDecl) {
  4295. if (pieceIndex > 0)
  4296. return clang_getNullRange();
  4297. if (const ImportDecl *ImportD =
  4298. dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
  4299. ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
  4300. if (!Locs.empty())
  4301. return cxloc::translateSourceRange(
  4302. Ctx, SourceRange(Locs.front(), Locs.back()));
  4303. }
  4304. return clang_getNullRange();
  4305. }
  4306. if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
  4307. C.kind == CXCursor_ConversionFunction ||
  4308. C.kind == CXCursor_FunctionDecl) {
  4309. if (pieceIndex > 0)
  4310. return clang_getNullRange();
  4311. if (const FunctionDecl *FD =
  4312. dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
  4313. DeclarationNameInfo FunctionName = FD->getNameInfo();
  4314. return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
  4315. }
  4316. return clang_getNullRange();
  4317. }
  4318. // FIXME: A CXCursor_InclusionDirective should give the location of the
  4319. // filename, but we don't keep track of this.
  4320. // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
  4321. // but we don't keep track of this.
  4322. // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
  4323. // but we don't keep track of this.
  4324. // Default handling, give the location of the cursor.
  4325. if (pieceIndex > 0)
  4326. return clang_getNullRange();
  4327. CXSourceLocation CXLoc = clang_getCursorLocation(C);
  4328. SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
  4329. return cxloc::translateSourceRange(Ctx, Loc);
  4330. }
  4331. CXString clang_Cursor_getMangling(CXCursor C) {
  4332. if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
  4333. return cxstring::createEmpty();
  4334. // Mangling only works for functions and variables.
  4335. const Decl *D = getCursorDecl(C);
  4336. if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
  4337. return cxstring::createEmpty();
  4338. ASTContext &Ctx = D->getASTContext();
  4339. ASTNameGenerator ASTNameGen(Ctx);
  4340. return cxstring::createDup(ASTNameGen.getName(D));
  4341. }
  4342. CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
  4343. if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
  4344. return nullptr;
  4345. const Decl *D = getCursorDecl(C);
  4346. if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
  4347. return nullptr;
  4348. ASTContext &Ctx = D->getASTContext();
  4349. ASTNameGenerator ASTNameGen(Ctx);
  4350. std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
  4351. return cxstring::createSet(Manglings);
  4352. }
  4353. CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
  4354. if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
  4355. return nullptr;
  4356. const Decl *D = getCursorDecl(C);
  4357. if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
  4358. return nullptr;
  4359. ASTContext &Ctx = D->getASTContext();
  4360. ASTNameGenerator ASTNameGen(Ctx);
  4361. std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
  4362. return cxstring::createSet(Manglings);
  4363. }
  4364. CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
  4365. if (clang_Cursor_isNull(C))
  4366. return nullptr;
  4367. return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
  4368. }
  4369. void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
  4370. if (Policy)
  4371. delete static_cast<PrintingPolicy *>(Policy);
  4372. }
  4373. unsigned
  4374. clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
  4375. enum CXPrintingPolicyProperty Property) {
  4376. if (!Policy)
  4377. return 0;
  4378. PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
  4379. switch (Property) {
  4380. case CXPrintingPolicy_Indentation:
  4381. return P->Indentation;
  4382. case CXPrintingPolicy_SuppressSpecifiers:
  4383. return P->SuppressSpecifiers;
  4384. case CXPrintingPolicy_SuppressTagKeyword:
  4385. return P->SuppressTagKeyword;
  4386. case CXPrintingPolicy_IncludeTagDefinition:
  4387. return P->IncludeTagDefinition;
  4388. case CXPrintingPolicy_SuppressScope:
  4389. return P->SuppressScope;
  4390. case CXPrintingPolicy_SuppressUnwrittenScope:
  4391. return P->SuppressUnwrittenScope;
  4392. case CXPrintingPolicy_SuppressInitializers:
  4393. return P->SuppressInitializers;
  4394. case CXPrintingPolicy_ConstantArraySizeAsWritten:
  4395. return P->ConstantArraySizeAsWritten;
  4396. case CXPrintingPolicy_AnonymousTagLocations:
  4397. return P->AnonymousTagLocations;
  4398. case CXPrintingPolicy_SuppressStrongLifetime:
  4399. return P->SuppressStrongLifetime;
  4400. case CXPrintingPolicy_SuppressLifetimeQualifiers:
  4401. return P->SuppressLifetimeQualifiers;
  4402. case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
  4403. return P->SuppressTemplateArgsInCXXConstructors;
  4404. case CXPrintingPolicy_Bool:
  4405. return P->Bool;
  4406. case CXPrintingPolicy_Restrict:
  4407. return P->Restrict;
  4408. case CXPrintingPolicy_Alignof:
  4409. return P->Alignof;
  4410. case CXPrintingPolicy_UnderscoreAlignof:
  4411. return P->UnderscoreAlignof;
  4412. case CXPrintingPolicy_UseVoidForZeroParams:
  4413. return P->UseVoidForZeroParams;
  4414. case CXPrintingPolicy_TerseOutput:
  4415. return P->TerseOutput;
  4416. case CXPrintingPolicy_PolishForDeclaration:
  4417. return P->PolishForDeclaration;
  4418. case CXPrintingPolicy_Half:
  4419. return P->Half;
  4420. case CXPrintingPolicy_MSWChar:
  4421. return P->MSWChar;
  4422. case CXPrintingPolicy_IncludeNewlines:
  4423. return P->IncludeNewlines;
  4424. case CXPrintingPolicy_MSVCFormatting:
  4425. return P->MSVCFormatting;
  4426. case CXPrintingPolicy_ConstantsAsWritten:
  4427. return P->ConstantsAsWritten;
  4428. case CXPrintingPolicy_SuppressImplicitBase:
  4429. return P->SuppressImplicitBase;
  4430. case CXPrintingPolicy_FullyQualifiedName:
  4431. return P->FullyQualifiedName;
  4432. }
  4433. assert(false && "Invalid CXPrintingPolicyProperty");
  4434. return 0;
  4435. }
  4436. void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
  4437. enum CXPrintingPolicyProperty Property,
  4438. unsigned Value) {
  4439. if (!Policy)
  4440. return;
  4441. PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
  4442. switch (Property) {
  4443. case CXPrintingPolicy_Indentation:
  4444. P->Indentation = Value;
  4445. return;
  4446. case CXPrintingPolicy_SuppressSpecifiers:
  4447. P->SuppressSpecifiers = Value;
  4448. return;
  4449. case CXPrintingPolicy_SuppressTagKeyword:
  4450. P->SuppressTagKeyword = Value;
  4451. return;
  4452. case CXPrintingPolicy_IncludeTagDefinition:
  4453. P->IncludeTagDefinition = Value;
  4454. return;
  4455. case CXPrintingPolicy_SuppressScope:
  4456. P->SuppressScope = Value;
  4457. return;
  4458. case CXPrintingPolicy_SuppressUnwrittenScope:
  4459. P->SuppressUnwrittenScope = Value;
  4460. return;
  4461. case CXPrintingPolicy_SuppressInitializers:
  4462. P->SuppressInitializers = Value;
  4463. return;
  4464. case CXPrintingPolicy_ConstantArraySizeAsWritten:
  4465. P->ConstantArraySizeAsWritten = Value;
  4466. return;
  4467. case CXPrintingPolicy_AnonymousTagLocations:
  4468. P->AnonymousTagLocations = Value;
  4469. return;
  4470. case CXPrintingPolicy_SuppressStrongLifetime:
  4471. P->SuppressStrongLifetime = Value;
  4472. return;
  4473. case CXPrintingPolicy_SuppressLifetimeQualifiers:
  4474. P->SuppressLifetimeQualifiers = Value;
  4475. return;
  4476. case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
  4477. P->SuppressTemplateArgsInCXXConstructors = Value;
  4478. return;
  4479. case CXPrintingPolicy_Bool:
  4480. P->Bool = Value;
  4481. return;
  4482. case CXPrintingPolicy_Restrict:
  4483. P->Restrict = Value;
  4484. return;
  4485. case CXPrintingPolicy_Alignof:
  4486. P->Alignof = Value;
  4487. return;
  4488. case CXPrintingPolicy_UnderscoreAlignof:
  4489. P->UnderscoreAlignof = Value;
  4490. return;
  4491. case CXPrintingPolicy_UseVoidForZeroParams:
  4492. P->UseVoidForZeroParams = Value;
  4493. return;
  4494. case CXPrintingPolicy_TerseOutput:
  4495. P->TerseOutput = Value;
  4496. return;
  4497. case CXPrintingPolicy_PolishForDeclaration:
  4498. P->PolishForDeclaration = Value;
  4499. return;
  4500. case CXPrintingPolicy_Half:
  4501. P->Half = Value;
  4502. return;
  4503. case CXPrintingPolicy_MSWChar:
  4504. P->MSWChar = Value;
  4505. return;
  4506. case CXPrintingPolicy_IncludeNewlines:
  4507. P->IncludeNewlines = Value;
  4508. return;
  4509. case CXPrintingPolicy_MSVCFormatting:
  4510. P->MSVCFormatting = Value;
  4511. return;
  4512. case CXPrintingPolicy_ConstantsAsWritten:
  4513. P->ConstantsAsWritten = Value;
  4514. return;
  4515. case CXPrintingPolicy_SuppressImplicitBase:
  4516. P->SuppressImplicitBase = Value;
  4517. return;
  4518. case CXPrintingPolicy_FullyQualifiedName:
  4519. P->FullyQualifiedName = Value;
  4520. return;
  4521. }
  4522. assert(false && "Invalid CXPrintingPolicyProperty");
  4523. }
  4524. CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
  4525. if (clang_Cursor_isNull(C))
  4526. return cxstring::createEmpty();
  4527. if (clang_isDeclaration(C.kind)) {
  4528. const Decl *D = getCursorDecl(C);
  4529. if (!D)
  4530. return cxstring::createEmpty();
  4531. SmallString<128> Str;
  4532. llvm::raw_svector_ostream OS(Str);
  4533. PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
  4534. D->print(OS, UserPolicy ? *UserPolicy
  4535. : getCursorContext(C).getPrintingPolicy());
  4536. return cxstring::createDup(OS.str());
  4537. }
  4538. return cxstring::createEmpty();
  4539. }
  4540. CXString clang_getCursorDisplayName(CXCursor C) {
  4541. if (!clang_isDeclaration(C.kind))
  4542. return clang_getCursorSpelling(C);
  4543. const Decl *D = getCursorDecl(C);
  4544. if (!D)
  4545. return cxstring::createEmpty();
  4546. PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
  4547. if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  4548. D = FunTmpl->getTemplatedDecl();
  4549. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  4550. SmallString<64> Str;
  4551. llvm::raw_svector_ostream OS(Str);
  4552. OS << *Function;
  4553. if (Function->getPrimaryTemplate())
  4554. OS << "<>";
  4555. OS << "(";
  4556. for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
  4557. if (I)
  4558. OS << ", ";
  4559. OS << Function->getParamDecl(I)->getType().getAsString(Policy);
  4560. }
  4561. if (Function->isVariadic()) {
  4562. if (Function->getNumParams())
  4563. OS << ", ";
  4564. OS << "...";
  4565. }
  4566. OS << ")";
  4567. return cxstring::createDup(OS.str());
  4568. }
  4569. if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
  4570. SmallString<64> Str;
  4571. llvm::raw_svector_ostream OS(Str);
  4572. OS << *ClassTemplate;
  4573. OS << "<";
  4574. TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
  4575. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  4576. if (I)
  4577. OS << ", ";
  4578. NamedDecl *Param = Params->getParam(I);
  4579. if (Param->getIdentifier()) {
  4580. OS << Param->getIdentifier()->getName();
  4581. continue;
  4582. }
  4583. // There is no parameter name, which makes this tricky. Try to come up
  4584. // with something useful that isn't too long.
  4585. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  4586. if (const auto *TC = TTP->getTypeConstraint()) {
  4587. TC->getConceptNameInfo().printName(OS, Policy);
  4588. if (TC->hasExplicitTemplateArgs())
  4589. OS << "<...>";
  4590. } else
  4591. OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class");
  4592. else if (NonTypeTemplateParmDecl *NTTP =
  4593. dyn_cast<NonTypeTemplateParmDecl>(Param))
  4594. OS << NTTP->getType().getAsString(Policy);
  4595. else
  4596. OS << "template<...> class";
  4597. }
  4598. OS << ">";
  4599. return cxstring::createDup(OS.str());
  4600. }
  4601. if (const ClassTemplateSpecializationDecl *ClassSpec =
  4602. dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  4603. // If the type was explicitly written, use that.
  4604. if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
  4605. return cxstring::createDup(TSInfo->getType().getAsString(Policy));
  4606. SmallString<128> Str;
  4607. llvm::raw_svector_ostream OS(Str);
  4608. OS << *ClassSpec;
  4609. printTemplateArgumentList(
  4610. OS, ClassSpec->getTemplateArgs().asArray(), Policy,
  4611. ClassSpec->getSpecializedTemplate()->getTemplateParameters());
  4612. return cxstring::createDup(OS.str());
  4613. }
  4614. return clang_getCursorSpelling(C);
  4615. }
  4616. CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
  4617. switch (Kind) {
  4618. case CXCursor_FunctionDecl:
  4619. return cxstring::createRef("FunctionDecl");
  4620. case CXCursor_TypedefDecl:
  4621. return cxstring::createRef("TypedefDecl");
  4622. case CXCursor_EnumDecl:
  4623. return cxstring::createRef("EnumDecl");
  4624. case CXCursor_EnumConstantDecl:
  4625. return cxstring::createRef("EnumConstantDecl");
  4626. case CXCursor_StructDecl:
  4627. return cxstring::createRef("StructDecl");
  4628. case CXCursor_UnionDecl:
  4629. return cxstring::createRef("UnionDecl");
  4630. case CXCursor_ClassDecl:
  4631. return cxstring::createRef("ClassDecl");
  4632. case CXCursor_FieldDecl:
  4633. return cxstring::createRef("FieldDecl");
  4634. case CXCursor_VarDecl:
  4635. return cxstring::createRef("VarDecl");
  4636. case CXCursor_ParmDecl:
  4637. return cxstring::createRef("ParmDecl");
  4638. case CXCursor_ObjCInterfaceDecl:
  4639. return cxstring::createRef("ObjCInterfaceDecl");
  4640. case CXCursor_ObjCCategoryDecl:
  4641. return cxstring::createRef("ObjCCategoryDecl");
  4642. case CXCursor_ObjCProtocolDecl:
  4643. return cxstring::createRef("ObjCProtocolDecl");
  4644. case CXCursor_ObjCPropertyDecl:
  4645. return cxstring::createRef("ObjCPropertyDecl");
  4646. case CXCursor_ObjCIvarDecl:
  4647. return cxstring::createRef("ObjCIvarDecl");
  4648. case CXCursor_ObjCInstanceMethodDecl:
  4649. return cxstring::createRef("ObjCInstanceMethodDecl");
  4650. case CXCursor_ObjCClassMethodDecl:
  4651. return cxstring::createRef("ObjCClassMethodDecl");
  4652. case CXCursor_ObjCImplementationDecl:
  4653. return cxstring::createRef("ObjCImplementationDecl");
  4654. case CXCursor_ObjCCategoryImplDecl:
  4655. return cxstring::createRef("ObjCCategoryImplDecl");
  4656. case CXCursor_CXXMethod:
  4657. return cxstring::createRef("CXXMethod");
  4658. case CXCursor_UnexposedDecl:
  4659. return cxstring::createRef("UnexposedDecl");
  4660. case CXCursor_ObjCSuperClassRef:
  4661. return cxstring::createRef("ObjCSuperClassRef");
  4662. case CXCursor_ObjCProtocolRef:
  4663. return cxstring::createRef("ObjCProtocolRef");
  4664. case CXCursor_ObjCClassRef:
  4665. return cxstring::createRef("ObjCClassRef");
  4666. case CXCursor_TypeRef:
  4667. return cxstring::createRef("TypeRef");
  4668. case CXCursor_TemplateRef:
  4669. return cxstring::createRef("TemplateRef");
  4670. case CXCursor_NamespaceRef:
  4671. return cxstring::createRef("NamespaceRef");
  4672. case CXCursor_MemberRef:
  4673. return cxstring::createRef("MemberRef");
  4674. case CXCursor_LabelRef:
  4675. return cxstring::createRef("LabelRef");
  4676. case CXCursor_OverloadedDeclRef:
  4677. return cxstring::createRef("OverloadedDeclRef");
  4678. case CXCursor_VariableRef:
  4679. return cxstring::createRef("VariableRef");
  4680. case CXCursor_IntegerLiteral:
  4681. return cxstring::createRef("IntegerLiteral");
  4682. case CXCursor_FixedPointLiteral:
  4683. return cxstring::createRef("FixedPointLiteral");
  4684. case CXCursor_FloatingLiteral:
  4685. return cxstring::createRef("FloatingLiteral");
  4686. case CXCursor_ImaginaryLiteral:
  4687. return cxstring::createRef("ImaginaryLiteral");
  4688. case CXCursor_StringLiteral:
  4689. return cxstring::createRef("StringLiteral");
  4690. case CXCursor_CharacterLiteral:
  4691. return cxstring::createRef("CharacterLiteral");
  4692. case CXCursor_ParenExpr:
  4693. return cxstring::createRef("ParenExpr");
  4694. case CXCursor_UnaryOperator:
  4695. return cxstring::createRef("UnaryOperator");
  4696. case CXCursor_ArraySubscriptExpr:
  4697. return cxstring::createRef("ArraySubscriptExpr");
  4698. case CXCursor_OMPArraySectionExpr:
  4699. return cxstring::createRef("OMPArraySectionExpr");
  4700. case CXCursor_OMPArrayShapingExpr:
  4701. return cxstring::createRef("OMPArrayShapingExpr");
  4702. case CXCursor_OMPIteratorExpr:
  4703. return cxstring::createRef("OMPIteratorExpr");
  4704. case CXCursor_BinaryOperator:
  4705. return cxstring::createRef("BinaryOperator");
  4706. case CXCursor_CompoundAssignOperator:
  4707. return cxstring::createRef("CompoundAssignOperator");
  4708. case CXCursor_ConditionalOperator:
  4709. return cxstring::createRef("ConditionalOperator");
  4710. case CXCursor_CStyleCastExpr:
  4711. return cxstring::createRef("CStyleCastExpr");
  4712. case CXCursor_CompoundLiteralExpr:
  4713. return cxstring::createRef("CompoundLiteralExpr");
  4714. case CXCursor_InitListExpr:
  4715. return cxstring::createRef("InitListExpr");
  4716. case CXCursor_AddrLabelExpr:
  4717. return cxstring::createRef("AddrLabelExpr");
  4718. case CXCursor_StmtExpr:
  4719. return cxstring::createRef("StmtExpr");
  4720. case CXCursor_GenericSelectionExpr:
  4721. return cxstring::createRef("GenericSelectionExpr");
  4722. case CXCursor_GNUNullExpr:
  4723. return cxstring::createRef("GNUNullExpr");
  4724. case CXCursor_CXXStaticCastExpr:
  4725. return cxstring::createRef("CXXStaticCastExpr");
  4726. case CXCursor_CXXDynamicCastExpr:
  4727. return cxstring::createRef("CXXDynamicCastExpr");
  4728. case CXCursor_CXXReinterpretCastExpr:
  4729. return cxstring::createRef("CXXReinterpretCastExpr");
  4730. case CXCursor_CXXConstCastExpr:
  4731. return cxstring::createRef("CXXConstCastExpr");
  4732. case CXCursor_CXXFunctionalCastExpr:
  4733. return cxstring::createRef("CXXFunctionalCastExpr");
  4734. case CXCursor_CXXAddrspaceCastExpr:
  4735. return cxstring::createRef("CXXAddrspaceCastExpr");
  4736. case CXCursor_CXXTypeidExpr:
  4737. return cxstring::createRef("CXXTypeidExpr");
  4738. case CXCursor_CXXBoolLiteralExpr:
  4739. return cxstring::createRef("CXXBoolLiteralExpr");
  4740. case CXCursor_CXXNullPtrLiteralExpr:
  4741. return cxstring::createRef("CXXNullPtrLiteralExpr");
  4742. case CXCursor_CXXThisExpr:
  4743. return cxstring::createRef("CXXThisExpr");
  4744. case CXCursor_CXXThrowExpr:
  4745. return cxstring::createRef("CXXThrowExpr");
  4746. case CXCursor_CXXNewExpr:
  4747. return cxstring::createRef("CXXNewExpr");
  4748. case CXCursor_CXXDeleteExpr:
  4749. return cxstring::createRef("CXXDeleteExpr");
  4750. case CXCursor_UnaryExpr:
  4751. return cxstring::createRef("UnaryExpr");
  4752. case CXCursor_ObjCStringLiteral:
  4753. return cxstring::createRef("ObjCStringLiteral");
  4754. case CXCursor_ObjCBoolLiteralExpr:
  4755. return cxstring::createRef("ObjCBoolLiteralExpr");
  4756. case CXCursor_ObjCAvailabilityCheckExpr:
  4757. return cxstring::createRef("ObjCAvailabilityCheckExpr");
  4758. case CXCursor_ObjCSelfExpr:
  4759. return cxstring::createRef("ObjCSelfExpr");
  4760. case CXCursor_ObjCEncodeExpr:
  4761. return cxstring::createRef("ObjCEncodeExpr");
  4762. case CXCursor_ObjCSelectorExpr:
  4763. return cxstring::createRef("ObjCSelectorExpr");
  4764. case CXCursor_ObjCProtocolExpr:
  4765. return cxstring::createRef("ObjCProtocolExpr");
  4766. case CXCursor_ObjCBridgedCastExpr:
  4767. return cxstring::createRef("ObjCBridgedCastExpr");
  4768. case CXCursor_BlockExpr:
  4769. return cxstring::createRef("BlockExpr");
  4770. case CXCursor_PackExpansionExpr:
  4771. return cxstring::createRef("PackExpansionExpr");
  4772. case CXCursor_SizeOfPackExpr:
  4773. return cxstring::createRef("SizeOfPackExpr");
  4774. case CXCursor_LambdaExpr:
  4775. return cxstring::createRef("LambdaExpr");
  4776. case CXCursor_UnexposedExpr:
  4777. return cxstring::createRef("UnexposedExpr");
  4778. case CXCursor_DeclRefExpr:
  4779. return cxstring::createRef("DeclRefExpr");
  4780. case CXCursor_MemberRefExpr:
  4781. return cxstring::createRef("MemberRefExpr");
  4782. case CXCursor_CallExpr:
  4783. return cxstring::createRef("CallExpr");
  4784. case CXCursor_ObjCMessageExpr:
  4785. return cxstring::createRef("ObjCMessageExpr");
  4786. case CXCursor_BuiltinBitCastExpr:
  4787. return cxstring::createRef("BuiltinBitCastExpr");
  4788. case CXCursor_ConceptSpecializationExpr:
  4789. return cxstring::createRef("ConceptSpecializationExpr");
  4790. case CXCursor_RequiresExpr:
  4791. return cxstring::createRef("RequiresExpr");
  4792. case CXCursor_CXXParenListInitExpr:
  4793. return cxstring::createRef("CXXParenListInitExpr");
  4794. case CXCursor_UnexposedStmt:
  4795. return cxstring::createRef("UnexposedStmt");
  4796. case CXCursor_DeclStmt:
  4797. return cxstring::createRef("DeclStmt");
  4798. case CXCursor_LabelStmt:
  4799. return cxstring::createRef("LabelStmt");
  4800. case CXCursor_CompoundStmt:
  4801. return cxstring::createRef("CompoundStmt");
  4802. case CXCursor_CaseStmt:
  4803. return cxstring::createRef("CaseStmt");
  4804. case CXCursor_DefaultStmt:
  4805. return cxstring::createRef("DefaultStmt");
  4806. case CXCursor_IfStmt:
  4807. return cxstring::createRef("IfStmt");
  4808. case CXCursor_SwitchStmt:
  4809. return cxstring::createRef("SwitchStmt");
  4810. case CXCursor_WhileStmt:
  4811. return cxstring::createRef("WhileStmt");
  4812. case CXCursor_DoStmt:
  4813. return cxstring::createRef("DoStmt");
  4814. case CXCursor_ForStmt:
  4815. return cxstring::createRef("ForStmt");
  4816. case CXCursor_GotoStmt:
  4817. return cxstring::createRef("GotoStmt");
  4818. case CXCursor_IndirectGotoStmt:
  4819. return cxstring::createRef("IndirectGotoStmt");
  4820. case CXCursor_ContinueStmt:
  4821. return cxstring::createRef("ContinueStmt");
  4822. case CXCursor_BreakStmt:
  4823. return cxstring::createRef("BreakStmt");
  4824. case CXCursor_ReturnStmt:
  4825. return cxstring::createRef("ReturnStmt");
  4826. case CXCursor_GCCAsmStmt:
  4827. return cxstring::createRef("GCCAsmStmt");
  4828. case CXCursor_MSAsmStmt:
  4829. return cxstring::createRef("MSAsmStmt");
  4830. case CXCursor_ObjCAtTryStmt:
  4831. return cxstring::createRef("ObjCAtTryStmt");
  4832. case CXCursor_ObjCAtCatchStmt:
  4833. return cxstring::createRef("ObjCAtCatchStmt");
  4834. case CXCursor_ObjCAtFinallyStmt:
  4835. return cxstring::createRef("ObjCAtFinallyStmt");
  4836. case CXCursor_ObjCAtThrowStmt:
  4837. return cxstring::createRef("ObjCAtThrowStmt");
  4838. case CXCursor_ObjCAtSynchronizedStmt:
  4839. return cxstring::createRef("ObjCAtSynchronizedStmt");
  4840. case CXCursor_ObjCAutoreleasePoolStmt:
  4841. return cxstring::createRef("ObjCAutoreleasePoolStmt");
  4842. case CXCursor_ObjCForCollectionStmt:
  4843. return cxstring::createRef("ObjCForCollectionStmt");
  4844. case CXCursor_CXXCatchStmt:
  4845. return cxstring::createRef("CXXCatchStmt");
  4846. case CXCursor_CXXTryStmt:
  4847. return cxstring::createRef("CXXTryStmt");
  4848. case CXCursor_CXXForRangeStmt:
  4849. return cxstring::createRef("CXXForRangeStmt");
  4850. case CXCursor_SEHTryStmt:
  4851. return cxstring::createRef("SEHTryStmt");
  4852. case CXCursor_SEHExceptStmt:
  4853. return cxstring::createRef("SEHExceptStmt");
  4854. case CXCursor_SEHFinallyStmt:
  4855. return cxstring::createRef("SEHFinallyStmt");
  4856. case CXCursor_SEHLeaveStmt:
  4857. return cxstring::createRef("SEHLeaveStmt");
  4858. case CXCursor_NullStmt:
  4859. return cxstring::createRef("NullStmt");
  4860. case CXCursor_InvalidFile:
  4861. return cxstring::createRef("InvalidFile");
  4862. case CXCursor_InvalidCode:
  4863. return cxstring::createRef("InvalidCode");
  4864. case CXCursor_NoDeclFound:
  4865. return cxstring::createRef("NoDeclFound");
  4866. case CXCursor_NotImplemented:
  4867. return cxstring::createRef("NotImplemented");
  4868. case CXCursor_TranslationUnit:
  4869. return cxstring::createRef("TranslationUnit");
  4870. case CXCursor_UnexposedAttr:
  4871. return cxstring::createRef("UnexposedAttr");
  4872. case CXCursor_IBActionAttr:
  4873. return cxstring::createRef("attribute(ibaction)");
  4874. case CXCursor_IBOutletAttr:
  4875. return cxstring::createRef("attribute(iboutlet)");
  4876. case CXCursor_IBOutletCollectionAttr:
  4877. return cxstring::createRef("attribute(iboutletcollection)");
  4878. case CXCursor_CXXFinalAttr:
  4879. return cxstring::createRef("attribute(final)");
  4880. case CXCursor_CXXOverrideAttr:
  4881. return cxstring::createRef("attribute(override)");
  4882. case CXCursor_AnnotateAttr:
  4883. return cxstring::createRef("attribute(annotate)");
  4884. case CXCursor_AsmLabelAttr:
  4885. return cxstring::createRef("asm label");
  4886. case CXCursor_PackedAttr:
  4887. return cxstring::createRef("attribute(packed)");
  4888. case CXCursor_PureAttr:
  4889. return cxstring::createRef("attribute(pure)");
  4890. case CXCursor_ConstAttr:
  4891. return cxstring::createRef("attribute(const)");
  4892. case CXCursor_NoDuplicateAttr:
  4893. return cxstring::createRef("attribute(noduplicate)");
  4894. case CXCursor_CUDAConstantAttr:
  4895. return cxstring::createRef("attribute(constant)");
  4896. case CXCursor_CUDADeviceAttr:
  4897. return cxstring::createRef("attribute(device)");
  4898. case CXCursor_CUDAGlobalAttr:
  4899. return cxstring::createRef("attribute(global)");
  4900. case CXCursor_CUDAHostAttr:
  4901. return cxstring::createRef("attribute(host)");
  4902. case CXCursor_CUDASharedAttr:
  4903. return cxstring::createRef("attribute(shared)");
  4904. case CXCursor_VisibilityAttr:
  4905. return cxstring::createRef("attribute(visibility)");
  4906. case CXCursor_DLLExport:
  4907. return cxstring::createRef("attribute(dllexport)");
  4908. case CXCursor_DLLImport:
  4909. return cxstring::createRef("attribute(dllimport)");
  4910. case CXCursor_NSReturnsRetained:
  4911. return cxstring::createRef("attribute(ns_returns_retained)");
  4912. case CXCursor_NSReturnsNotRetained:
  4913. return cxstring::createRef("attribute(ns_returns_not_retained)");
  4914. case CXCursor_NSReturnsAutoreleased:
  4915. return cxstring::createRef("attribute(ns_returns_autoreleased)");
  4916. case CXCursor_NSConsumesSelf:
  4917. return cxstring::createRef("attribute(ns_consumes_self)");
  4918. case CXCursor_NSConsumed:
  4919. return cxstring::createRef("attribute(ns_consumed)");
  4920. case CXCursor_ObjCException:
  4921. return cxstring::createRef("attribute(objc_exception)");
  4922. case CXCursor_ObjCNSObject:
  4923. return cxstring::createRef("attribute(NSObject)");
  4924. case CXCursor_ObjCIndependentClass:
  4925. return cxstring::createRef("attribute(objc_independent_class)");
  4926. case CXCursor_ObjCPreciseLifetime:
  4927. return cxstring::createRef("attribute(objc_precise_lifetime)");
  4928. case CXCursor_ObjCReturnsInnerPointer:
  4929. return cxstring::createRef("attribute(objc_returns_inner_pointer)");
  4930. case CXCursor_ObjCRequiresSuper:
  4931. return cxstring::createRef("attribute(objc_requires_super)");
  4932. case CXCursor_ObjCRootClass:
  4933. return cxstring::createRef("attribute(objc_root_class)");
  4934. case CXCursor_ObjCSubclassingRestricted:
  4935. return cxstring::createRef("attribute(objc_subclassing_restricted)");
  4936. case CXCursor_ObjCExplicitProtocolImpl:
  4937. return cxstring::createRef(
  4938. "attribute(objc_protocol_requires_explicit_implementation)");
  4939. case CXCursor_ObjCDesignatedInitializer:
  4940. return cxstring::createRef("attribute(objc_designated_initializer)");
  4941. case CXCursor_ObjCRuntimeVisible:
  4942. return cxstring::createRef("attribute(objc_runtime_visible)");
  4943. case CXCursor_ObjCBoxable:
  4944. return cxstring::createRef("attribute(objc_boxable)");
  4945. case CXCursor_FlagEnum:
  4946. return cxstring::createRef("attribute(flag_enum)");
  4947. case CXCursor_PreprocessingDirective:
  4948. return cxstring::createRef("preprocessing directive");
  4949. case CXCursor_MacroDefinition:
  4950. return cxstring::createRef("macro definition");
  4951. case CXCursor_MacroExpansion:
  4952. return cxstring::createRef("macro expansion");
  4953. case CXCursor_InclusionDirective:
  4954. return cxstring::createRef("inclusion directive");
  4955. case CXCursor_Namespace:
  4956. return cxstring::createRef("Namespace");
  4957. case CXCursor_LinkageSpec:
  4958. return cxstring::createRef("LinkageSpec");
  4959. case CXCursor_CXXBaseSpecifier:
  4960. return cxstring::createRef("C++ base class specifier");
  4961. case CXCursor_Constructor:
  4962. return cxstring::createRef("CXXConstructor");
  4963. case CXCursor_Destructor:
  4964. return cxstring::createRef("CXXDestructor");
  4965. case CXCursor_ConversionFunction:
  4966. return cxstring::createRef("CXXConversion");
  4967. case CXCursor_TemplateTypeParameter:
  4968. return cxstring::createRef("TemplateTypeParameter");
  4969. case CXCursor_NonTypeTemplateParameter:
  4970. return cxstring::createRef("NonTypeTemplateParameter");
  4971. case CXCursor_TemplateTemplateParameter:
  4972. return cxstring::createRef("TemplateTemplateParameter");
  4973. case CXCursor_FunctionTemplate:
  4974. return cxstring::createRef("FunctionTemplate");
  4975. case CXCursor_ClassTemplate:
  4976. return cxstring::createRef("ClassTemplate");
  4977. case CXCursor_ClassTemplatePartialSpecialization:
  4978. return cxstring::createRef("ClassTemplatePartialSpecialization");
  4979. case CXCursor_NamespaceAlias:
  4980. return cxstring::createRef("NamespaceAlias");
  4981. case CXCursor_UsingDirective:
  4982. return cxstring::createRef("UsingDirective");
  4983. case CXCursor_UsingDeclaration:
  4984. return cxstring::createRef("UsingDeclaration");
  4985. case CXCursor_TypeAliasDecl:
  4986. return cxstring::createRef("TypeAliasDecl");
  4987. case CXCursor_ObjCSynthesizeDecl:
  4988. return cxstring::createRef("ObjCSynthesizeDecl");
  4989. case CXCursor_ObjCDynamicDecl:
  4990. return cxstring::createRef("ObjCDynamicDecl");
  4991. case CXCursor_CXXAccessSpecifier:
  4992. return cxstring::createRef("CXXAccessSpecifier");
  4993. case CXCursor_ModuleImportDecl:
  4994. return cxstring::createRef("ModuleImport");
  4995. case CXCursor_OMPCanonicalLoop:
  4996. return cxstring::createRef("OMPCanonicalLoop");
  4997. case CXCursor_OMPMetaDirective:
  4998. return cxstring::createRef("OMPMetaDirective");
  4999. case CXCursor_OMPParallelDirective:
  5000. return cxstring::createRef("OMPParallelDirective");
  5001. case CXCursor_OMPSimdDirective:
  5002. return cxstring::createRef("OMPSimdDirective");
  5003. case CXCursor_OMPTileDirective:
  5004. return cxstring::createRef("OMPTileDirective");
  5005. case CXCursor_OMPUnrollDirective:
  5006. return cxstring::createRef("OMPUnrollDirective");
  5007. case CXCursor_OMPForDirective:
  5008. return cxstring::createRef("OMPForDirective");
  5009. case CXCursor_OMPForSimdDirective:
  5010. return cxstring::createRef("OMPForSimdDirective");
  5011. case CXCursor_OMPSectionsDirective:
  5012. return cxstring::createRef("OMPSectionsDirective");
  5013. case CXCursor_OMPSectionDirective:
  5014. return cxstring::createRef("OMPSectionDirective");
  5015. case CXCursor_OMPSingleDirective:
  5016. return cxstring::createRef("OMPSingleDirective");
  5017. case CXCursor_OMPMasterDirective:
  5018. return cxstring::createRef("OMPMasterDirective");
  5019. case CXCursor_OMPCriticalDirective:
  5020. return cxstring::createRef("OMPCriticalDirective");
  5021. case CXCursor_OMPParallelForDirective:
  5022. return cxstring::createRef("OMPParallelForDirective");
  5023. case CXCursor_OMPParallelForSimdDirective:
  5024. return cxstring::createRef("OMPParallelForSimdDirective");
  5025. case CXCursor_OMPParallelMasterDirective:
  5026. return cxstring::createRef("OMPParallelMasterDirective");
  5027. case CXCursor_OMPParallelMaskedDirective:
  5028. return cxstring::createRef("OMPParallelMaskedDirective");
  5029. case CXCursor_OMPParallelSectionsDirective:
  5030. return cxstring::createRef("OMPParallelSectionsDirective");
  5031. case CXCursor_OMPTaskDirective:
  5032. return cxstring::createRef("OMPTaskDirective");
  5033. case CXCursor_OMPTaskyieldDirective:
  5034. return cxstring::createRef("OMPTaskyieldDirective");
  5035. case CXCursor_OMPBarrierDirective:
  5036. return cxstring::createRef("OMPBarrierDirective");
  5037. case CXCursor_OMPTaskwaitDirective:
  5038. return cxstring::createRef("OMPTaskwaitDirective");
  5039. case CXCursor_OMPErrorDirective:
  5040. return cxstring::createRef("OMPErrorDirective");
  5041. case CXCursor_OMPTaskgroupDirective:
  5042. return cxstring::createRef("OMPTaskgroupDirective");
  5043. case CXCursor_OMPFlushDirective:
  5044. return cxstring::createRef("OMPFlushDirective");
  5045. case CXCursor_OMPDepobjDirective:
  5046. return cxstring::createRef("OMPDepobjDirective");
  5047. case CXCursor_OMPScanDirective:
  5048. return cxstring::createRef("OMPScanDirective");
  5049. case CXCursor_OMPOrderedDirective:
  5050. return cxstring::createRef("OMPOrderedDirective");
  5051. case CXCursor_OMPAtomicDirective:
  5052. return cxstring::createRef("OMPAtomicDirective");
  5053. case CXCursor_OMPTargetDirective:
  5054. return cxstring::createRef("OMPTargetDirective");
  5055. case CXCursor_OMPTargetDataDirective:
  5056. return cxstring::createRef("OMPTargetDataDirective");
  5057. case CXCursor_OMPTargetEnterDataDirective:
  5058. return cxstring::createRef("OMPTargetEnterDataDirective");
  5059. case CXCursor_OMPTargetExitDataDirective:
  5060. return cxstring::createRef("OMPTargetExitDataDirective");
  5061. case CXCursor_OMPTargetParallelDirective:
  5062. return cxstring::createRef("OMPTargetParallelDirective");
  5063. case CXCursor_OMPTargetParallelForDirective:
  5064. return cxstring::createRef("OMPTargetParallelForDirective");
  5065. case CXCursor_OMPTargetUpdateDirective:
  5066. return cxstring::createRef("OMPTargetUpdateDirective");
  5067. case CXCursor_OMPTeamsDirective:
  5068. return cxstring::createRef("OMPTeamsDirective");
  5069. case CXCursor_OMPCancellationPointDirective:
  5070. return cxstring::createRef("OMPCancellationPointDirective");
  5071. case CXCursor_OMPCancelDirective:
  5072. return cxstring::createRef("OMPCancelDirective");
  5073. case CXCursor_OMPTaskLoopDirective:
  5074. return cxstring::createRef("OMPTaskLoopDirective");
  5075. case CXCursor_OMPTaskLoopSimdDirective:
  5076. return cxstring::createRef("OMPTaskLoopSimdDirective");
  5077. case CXCursor_OMPMasterTaskLoopDirective:
  5078. return cxstring::createRef("OMPMasterTaskLoopDirective");
  5079. case CXCursor_OMPMaskedTaskLoopDirective:
  5080. return cxstring::createRef("OMPMaskedTaskLoopDirective");
  5081. case CXCursor_OMPMasterTaskLoopSimdDirective:
  5082. return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
  5083. case CXCursor_OMPMaskedTaskLoopSimdDirective:
  5084. return cxstring::createRef("OMPMaskedTaskLoopSimdDirective");
  5085. case CXCursor_OMPParallelMasterTaskLoopDirective:
  5086. return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
  5087. case CXCursor_OMPParallelMaskedTaskLoopDirective:
  5088. return cxstring::createRef("OMPParallelMaskedTaskLoopDirective");
  5089. case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
  5090. return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
  5091. case CXCursor_OMPParallelMaskedTaskLoopSimdDirective:
  5092. return cxstring::createRef("OMPParallelMaskedTaskLoopSimdDirective");
  5093. case CXCursor_OMPDistributeDirective:
  5094. return cxstring::createRef("OMPDistributeDirective");
  5095. case CXCursor_OMPDistributeParallelForDirective:
  5096. return cxstring::createRef("OMPDistributeParallelForDirective");
  5097. case CXCursor_OMPDistributeParallelForSimdDirective:
  5098. return cxstring::createRef("OMPDistributeParallelForSimdDirective");
  5099. case CXCursor_OMPDistributeSimdDirective:
  5100. return cxstring::createRef("OMPDistributeSimdDirective");
  5101. case CXCursor_OMPTargetParallelForSimdDirective:
  5102. return cxstring::createRef("OMPTargetParallelForSimdDirective");
  5103. case CXCursor_OMPTargetSimdDirective:
  5104. return cxstring::createRef("OMPTargetSimdDirective");
  5105. case CXCursor_OMPTeamsDistributeDirective:
  5106. return cxstring::createRef("OMPTeamsDistributeDirective");
  5107. case CXCursor_OMPTeamsDistributeSimdDirective:
  5108. return cxstring::createRef("OMPTeamsDistributeSimdDirective");
  5109. case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
  5110. return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
  5111. case CXCursor_OMPTeamsDistributeParallelForDirective:
  5112. return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
  5113. case CXCursor_OMPTargetTeamsDirective:
  5114. return cxstring::createRef("OMPTargetTeamsDirective");
  5115. case CXCursor_OMPTargetTeamsDistributeDirective:
  5116. return cxstring::createRef("OMPTargetTeamsDistributeDirective");
  5117. case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
  5118. return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
  5119. case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
  5120. return cxstring::createRef(
  5121. "OMPTargetTeamsDistributeParallelForSimdDirective");
  5122. case CXCursor_OMPTargetTeamsDistributeSimdDirective:
  5123. return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
  5124. case CXCursor_OMPInteropDirective:
  5125. return cxstring::createRef("OMPInteropDirective");
  5126. case CXCursor_OMPDispatchDirective:
  5127. return cxstring::createRef("OMPDispatchDirective");
  5128. case CXCursor_OMPMaskedDirective:
  5129. return cxstring::createRef("OMPMaskedDirective");
  5130. case CXCursor_OMPGenericLoopDirective:
  5131. return cxstring::createRef("OMPGenericLoopDirective");
  5132. case CXCursor_OMPTeamsGenericLoopDirective:
  5133. return cxstring::createRef("OMPTeamsGenericLoopDirective");
  5134. case CXCursor_OMPTargetTeamsGenericLoopDirective:
  5135. return cxstring::createRef("OMPTargetTeamsGenericLoopDirective");
  5136. case CXCursor_OMPParallelGenericLoopDirective:
  5137. return cxstring::createRef("OMPParallelGenericLoopDirective");
  5138. case CXCursor_OMPTargetParallelGenericLoopDirective:
  5139. return cxstring::createRef("OMPTargetParallelGenericLoopDirective");
  5140. case CXCursor_OverloadCandidate:
  5141. return cxstring::createRef("OverloadCandidate");
  5142. case CXCursor_TypeAliasTemplateDecl:
  5143. return cxstring::createRef("TypeAliasTemplateDecl");
  5144. case CXCursor_StaticAssert:
  5145. return cxstring::createRef("StaticAssert");
  5146. case CXCursor_FriendDecl:
  5147. return cxstring::createRef("FriendDecl");
  5148. case CXCursor_ConvergentAttr:
  5149. return cxstring::createRef("attribute(convergent)");
  5150. case CXCursor_WarnUnusedAttr:
  5151. return cxstring::createRef("attribute(warn_unused)");
  5152. case CXCursor_WarnUnusedResultAttr:
  5153. return cxstring::createRef("attribute(warn_unused_result)");
  5154. case CXCursor_AlignedAttr:
  5155. return cxstring::createRef("attribute(aligned)");
  5156. case CXCursor_ConceptDecl:
  5157. return cxstring::createRef("ConceptDecl");
  5158. }
  5159. llvm_unreachable("Unhandled CXCursorKind");
  5160. }
  5161. struct GetCursorData {
  5162. SourceLocation TokenBeginLoc;
  5163. bool PointsAtMacroArgExpansion;
  5164. bool VisitedObjCPropertyImplDecl;
  5165. SourceLocation VisitedDeclaratorDeclStartLoc;
  5166. CXCursor &BestCursor;
  5167. GetCursorData(SourceManager &SM, SourceLocation tokenBegin,
  5168. CXCursor &outputCursor)
  5169. : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
  5170. PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
  5171. VisitedObjCPropertyImplDecl = false;
  5172. }
  5173. };
  5174. static enum CXChildVisitResult
  5175. GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
  5176. GetCursorData *Data = static_cast<GetCursorData *>(client_data);
  5177. CXCursor *BestCursor = &Data->BestCursor;
  5178. // If we point inside a macro argument we should provide info of what the
  5179. // token is so use the actual cursor, don't replace it with a macro expansion
  5180. // cursor.
  5181. if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
  5182. return CXChildVisit_Recurse;
  5183. if (clang_isDeclaration(cursor.kind)) {
  5184. // Avoid having the implicit methods override the property decls.
  5185. if (const ObjCMethodDecl *MD =
  5186. dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
  5187. if (MD->isImplicit())
  5188. return CXChildVisit_Break;
  5189. } else if (const ObjCInterfaceDecl *ID =
  5190. dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
  5191. // Check that when we have multiple @class references in the same line,
  5192. // that later ones do not override the previous ones.
  5193. // If we have:
  5194. // @class Foo, Bar;
  5195. // source ranges for both start at '@', so 'Bar' will end up overriding
  5196. // 'Foo' even though the cursor location was at 'Foo'.
  5197. if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
  5198. BestCursor->kind == CXCursor_ObjCClassRef)
  5199. if (const ObjCInterfaceDecl *PrevID =
  5200. dyn_cast_or_null<ObjCInterfaceDecl>(
  5201. getCursorDecl(*BestCursor))) {
  5202. if (PrevID != ID && !PrevID->isThisDeclarationADefinition() &&
  5203. !ID->isThisDeclarationADefinition())
  5204. return CXChildVisit_Break;
  5205. }
  5206. } else if (const DeclaratorDecl *DD =
  5207. dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
  5208. SourceLocation StartLoc = DD->getSourceRange().getBegin();
  5209. // Check that when we have multiple declarators in the same line,
  5210. // that later ones do not override the previous ones.
  5211. // If we have:
  5212. // int Foo, Bar;
  5213. // source ranges for both start at 'int', so 'Bar' will end up overriding
  5214. // 'Foo' even though the cursor location was at 'Foo'.
  5215. if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
  5216. return CXChildVisit_Break;
  5217. Data->VisitedDeclaratorDeclStartLoc = StartLoc;
  5218. } else if (const ObjCPropertyImplDecl *PropImp =
  5219. dyn_cast_or_null<ObjCPropertyImplDecl>(
  5220. getCursorDecl(cursor))) {
  5221. (void)PropImp;
  5222. // Check that when we have multiple @synthesize in the same line,
  5223. // that later ones do not override the previous ones.
  5224. // If we have:
  5225. // @synthesize Foo, Bar;
  5226. // source ranges for both start at '@', so 'Bar' will end up overriding
  5227. // 'Foo' even though the cursor location was at 'Foo'.
  5228. if (Data->VisitedObjCPropertyImplDecl)
  5229. return CXChildVisit_Break;
  5230. Data->VisitedObjCPropertyImplDecl = true;
  5231. }
  5232. }
  5233. if (clang_isExpression(cursor.kind) &&
  5234. clang_isDeclaration(BestCursor->kind)) {
  5235. if (const Decl *D = getCursorDecl(*BestCursor)) {
  5236. // Avoid having the cursor of an expression replace the declaration cursor
  5237. // when the expression source range overlaps the declaration range.
  5238. // This can happen for C++ constructor expressions whose range generally
  5239. // include the variable declaration, e.g.:
  5240. // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl
  5241. // cursor.
  5242. if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
  5243. D->getLocation() == Data->TokenBeginLoc)
  5244. return CXChildVisit_Break;
  5245. }
  5246. }
  5247. // If our current best cursor is the construction of a temporary object,
  5248. // don't replace that cursor with a type reference, because we want
  5249. // clang_getCursor() to point at the constructor.
  5250. if (clang_isExpression(BestCursor->kind) &&
  5251. isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
  5252. cursor.kind == CXCursor_TypeRef) {
  5253. // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
  5254. // as having the actual point on the type reference.
  5255. *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
  5256. return CXChildVisit_Recurse;
  5257. }
  5258. // If we already have an Objective-C superclass reference, don't
  5259. // update it further.
  5260. if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
  5261. return CXChildVisit_Break;
  5262. *BestCursor = cursor;
  5263. return CXChildVisit_Recurse;
  5264. }
  5265. CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
  5266. if (isNotUsableTU(TU)) {
  5267. LOG_BAD_TU(TU);
  5268. return clang_getNullCursor();
  5269. }
  5270. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5271. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  5272. SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
  5273. CXCursor Result = cxcursor::getCursor(TU, SLoc);
  5274. LOG_FUNC_SECTION {
  5275. CXFile SearchFile;
  5276. unsigned SearchLine, SearchColumn;
  5277. CXFile ResultFile;
  5278. unsigned ResultLine, ResultColumn;
  5279. CXString SearchFileName, ResultFileName, KindSpelling, USR;
  5280. const char *IsDef = clang_isCursorDefinition(Result) ? " (Definition)" : "";
  5281. CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
  5282. clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
  5283. nullptr);
  5284. clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn,
  5285. nullptr);
  5286. SearchFileName = clang_getFileName(SearchFile);
  5287. ResultFileName = clang_getFileName(ResultFile);
  5288. KindSpelling = clang_getCursorKindSpelling(Result.kind);
  5289. USR = clang_getCursorUSR(Result);
  5290. *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName),
  5291. SearchLine, SearchColumn,
  5292. clang_getCString(KindSpelling))
  5293. << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName),
  5294. ResultLine, ResultColumn, clang_getCString(USR),
  5295. IsDef);
  5296. clang_disposeString(SearchFileName);
  5297. clang_disposeString(ResultFileName);
  5298. clang_disposeString(KindSpelling);
  5299. clang_disposeString(USR);
  5300. CXCursor Definition = clang_getCursorDefinition(Result);
  5301. if (!clang_equalCursors(Definition, clang_getNullCursor())) {
  5302. CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
  5303. CXString DefinitionKindSpelling =
  5304. clang_getCursorKindSpelling(Definition.kind);
  5305. CXFile DefinitionFile;
  5306. unsigned DefinitionLine, DefinitionColumn;
  5307. clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine,
  5308. &DefinitionColumn, nullptr);
  5309. CXString DefinitionFileName = clang_getFileName(DefinitionFile);
  5310. *Log << llvm::format(" -> %s(%s:%d:%d)",
  5311. clang_getCString(DefinitionKindSpelling),
  5312. clang_getCString(DefinitionFileName), DefinitionLine,
  5313. DefinitionColumn);
  5314. clang_disposeString(DefinitionFileName);
  5315. clang_disposeString(DefinitionKindSpelling);
  5316. }
  5317. }
  5318. return Result;
  5319. }
  5320. CXCursor clang_getNullCursor(void) {
  5321. return MakeCXCursorInvalid(CXCursor_InvalidFile);
  5322. }
  5323. unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
  5324. // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
  5325. // can't set consistently. For example, when visiting a DeclStmt we will set
  5326. // it but we don't set it on the result of clang_getCursorDefinition for
  5327. // a reference of the same declaration.
  5328. // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
  5329. // when visiting a DeclStmt currently, the AST should be enhanced to be able
  5330. // to provide that kind of info.
  5331. if (clang_isDeclaration(X.kind))
  5332. X.data[1] = nullptr;
  5333. if (clang_isDeclaration(Y.kind))
  5334. Y.data[1] = nullptr;
  5335. return X == Y;
  5336. }
  5337. unsigned clang_hashCursor(CXCursor C) {
  5338. unsigned Index = 0;
  5339. if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
  5340. Index = 1;
  5341. return llvm::DenseMapInfo<std::pair<unsigned, const void *>>::getHashValue(
  5342. std::make_pair(C.kind, C.data[Index]));
  5343. }
  5344. unsigned clang_isInvalid(enum CXCursorKind K) {
  5345. return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
  5346. }
  5347. unsigned clang_isDeclaration(enum CXCursorKind K) {
  5348. return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
  5349. (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
  5350. }
  5351. unsigned clang_isInvalidDeclaration(CXCursor C) {
  5352. if (clang_isDeclaration(C.kind)) {
  5353. if (const Decl *D = getCursorDecl(C))
  5354. return D->isInvalidDecl();
  5355. }
  5356. return 0;
  5357. }
  5358. unsigned clang_isReference(enum CXCursorKind K) {
  5359. return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
  5360. }
  5361. unsigned clang_isExpression(enum CXCursorKind K) {
  5362. return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
  5363. }
  5364. unsigned clang_isStatement(enum CXCursorKind K) {
  5365. return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
  5366. }
  5367. unsigned clang_isAttribute(enum CXCursorKind K) {
  5368. return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
  5369. }
  5370. unsigned clang_isTranslationUnit(enum CXCursorKind K) {
  5371. return K == CXCursor_TranslationUnit;
  5372. }
  5373. unsigned clang_isPreprocessing(enum CXCursorKind K) {
  5374. return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
  5375. }
  5376. unsigned clang_isUnexposed(enum CXCursorKind K) {
  5377. switch (K) {
  5378. case CXCursor_UnexposedDecl:
  5379. case CXCursor_UnexposedExpr:
  5380. case CXCursor_UnexposedStmt:
  5381. case CXCursor_UnexposedAttr:
  5382. return true;
  5383. default:
  5384. return false;
  5385. }
  5386. }
  5387. CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; }
  5388. CXSourceLocation clang_getCursorLocation(CXCursor C) {
  5389. if (clang_isReference(C.kind)) {
  5390. switch (C.kind) {
  5391. case CXCursor_ObjCSuperClassRef: {
  5392. std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
  5393. getCursorObjCSuperClassRef(C);
  5394. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5395. }
  5396. case CXCursor_ObjCProtocolRef: {
  5397. std::pair<const ObjCProtocolDecl *, SourceLocation> P =
  5398. getCursorObjCProtocolRef(C);
  5399. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5400. }
  5401. case CXCursor_ObjCClassRef: {
  5402. std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
  5403. getCursorObjCClassRef(C);
  5404. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5405. }
  5406. case CXCursor_TypeRef: {
  5407. std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
  5408. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5409. }
  5410. case CXCursor_TemplateRef: {
  5411. std::pair<const TemplateDecl *, SourceLocation> P =
  5412. getCursorTemplateRef(C);
  5413. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5414. }
  5415. case CXCursor_NamespaceRef: {
  5416. std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
  5417. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5418. }
  5419. case CXCursor_MemberRef: {
  5420. std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
  5421. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5422. }
  5423. case CXCursor_VariableRef: {
  5424. std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
  5425. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5426. }
  5427. case CXCursor_CXXBaseSpecifier: {
  5428. const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
  5429. if (!BaseSpec)
  5430. return clang_getNullLocation();
  5431. if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
  5432. return cxloc::translateSourceLocation(
  5433. getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc());
  5434. return cxloc::translateSourceLocation(getCursorContext(C),
  5435. BaseSpec->getBeginLoc());
  5436. }
  5437. case CXCursor_LabelRef: {
  5438. std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
  5439. return cxloc::translateSourceLocation(getCursorContext(C), P.second);
  5440. }
  5441. case CXCursor_OverloadedDeclRef:
  5442. return cxloc::translateSourceLocation(
  5443. getCursorContext(C), getCursorOverloadedDeclRef(C).second);
  5444. default:
  5445. // FIXME: Need a way to enumerate all non-reference cases.
  5446. llvm_unreachable("Missed a reference kind");
  5447. }
  5448. }
  5449. if (clang_isExpression(C.kind))
  5450. return cxloc::translateSourceLocation(
  5451. getCursorContext(C), getLocationFromExpr(getCursorExpr(C)));
  5452. if (clang_isStatement(C.kind))
  5453. return cxloc::translateSourceLocation(getCursorContext(C),
  5454. getCursorStmt(C)->getBeginLoc());
  5455. if (C.kind == CXCursor_PreprocessingDirective) {
  5456. SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
  5457. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5458. }
  5459. if (C.kind == CXCursor_MacroExpansion) {
  5460. SourceLocation L =
  5461. cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
  5462. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5463. }
  5464. if (C.kind == CXCursor_MacroDefinition) {
  5465. SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
  5466. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5467. }
  5468. if (C.kind == CXCursor_InclusionDirective) {
  5469. SourceLocation L =
  5470. cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
  5471. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5472. }
  5473. if (clang_isAttribute(C.kind)) {
  5474. SourceLocation L = cxcursor::getCursorAttr(C)->getLocation();
  5475. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5476. }
  5477. if (!clang_isDeclaration(C.kind))
  5478. return clang_getNullLocation();
  5479. const Decl *D = getCursorDecl(C);
  5480. if (!D)
  5481. return clang_getNullLocation();
  5482. SourceLocation Loc = D->getLocation();
  5483. // FIXME: Multiple variables declared in a single declaration
  5484. // currently lack the information needed to correctly determine their
  5485. // ranges when accounting for the type-specifier. We use context
  5486. // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
  5487. // and if so, whether it is the first decl.
  5488. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  5489. if (!cxcursor::isFirstInDeclGroup(C))
  5490. Loc = VD->getLocation();
  5491. }
  5492. // For ObjC methods, give the start location of the method name.
  5493. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  5494. Loc = MD->getSelectorStartLoc();
  5495. return cxloc::translateSourceLocation(getCursorContext(C), Loc);
  5496. }
  5497. } // end extern "C"
  5498. CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
  5499. assert(TU);
  5500. // Guard against an invalid SourceLocation, or we may assert in one
  5501. // of the following calls.
  5502. if (SLoc.isInvalid())
  5503. return clang_getNullCursor();
  5504. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5505. // Translate the given source location to make it point at the beginning of
  5506. // the token under the cursor.
  5507. SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
  5508. CXXUnit->getASTContext().getLangOpts());
  5509. CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
  5510. if (SLoc.isValid()) {
  5511. GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
  5512. CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
  5513. /*VisitPreprocessorLast=*/true,
  5514. /*VisitIncludedEntities=*/false,
  5515. SourceLocation(SLoc));
  5516. CursorVis.visitFileRegion();
  5517. }
  5518. return Result;
  5519. }
  5520. static SourceRange getRawCursorExtent(CXCursor C) {
  5521. if (clang_isReference(C.kind)) {
  5522. switch (C.kind) {
  5523. case CXCursor_ObjCSuperClassRef:
  5524. return getCursorObjCSuperClassRef(C).second;
  5525. case CXCursor_ObjCProtocolRef:
  5526. return getCursorObjCProtocolRef(C).second;
  5527. case CXCursor_ObjCClassRef:
  5528. return getCursorObjCClassRef(C).second;
  5529. case CXCursor_TypeRef:
  5530. return getCursorTypeRef(C).second;
  5531. case CXCursor_TemplateRef:
  5532. return getCursorTemplateRef(C).second;
  5533. case CXCursor_NamespaceRef:
  5534. return getCursorNamespaceRef(C).second;
  5535. case CXCursor_MemberRef:
  5536. return getCursorMemberRef(C).second;
  5537. case CXCursor_CXXBaseSpecifier:
  5538. return getCursorCXXBaseSpecifier(C)->getSourceRange();
  5539. case CXCursor_LabelRef:
  5540. return getCursorLabelRef(C).second;
  5541. case CXCursor_OverloadedDeclRef:
  5542. return getCursorOverloadedDeclRef(C).second;
  5543. case CXCursor_VariableRef:
  5544. return getCursorVariableRef(C).second;
  5545. default:
  5546. // FIXME: Need a way to enumerate all non-reference cases.
  5547. llvm_unreachable("Missed a reference kind");
  5548. }
  5549. }
  5550. if (clang_isExpression(C.kind))
  5551. return getCursorExpr(C)->getSourceRange();
  5552. if (clang_isStatement(C.kind))
  5553. return getCursorStmt(C)->getSourceRange();
  5554. if (clang_isAttribute(C.kind))
  5555. return getCursorAttr(C)->getRange();
  5556. if (C.kind == CXCursor_PreprocessingDirective)
  5557. return cxcursor::getCursorPreprocessingDirective(C);
  5558. if (C.kind == CXCursor_MacroExpansion) {
  5559. ASTUnit *TU = getCursorASTUnit(C);
  5560. SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
  5561. return TU->mapRangeFromPreamble(Range);
  5562. }
  5563. if (C.kind == CXCursor_MacroDefinition) {
  5564. ASTUnit *TU = getCursorASTUnit(C);
  5565. SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
  5566. return TU->mapRangeFromPreamble(Range);
  5567. }
  5568. if (C.kind == CXCursor_InclusionDirective) {
  5569. ASTUnit *TU = getCursorASTUnit(C);
  5570. SourceRange Range =
  5571. cxcursor::getCursorInclusionDirective(C)->getSourceRange();
  5572. return TU->mapRangeFromPreamble(Range);
  5573. }
  5574. if (C.kind == CXCursor_TranslationUnit) {
  5575. ASTUnit *TU = getCursorASTUnit(C);
  5576. FileID MainID = TU->getSourceManager().getMainFileID();
  5577. SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
  5578. SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
  5579. return SourceRange(Start, End);
  5580. }
  5581. if (clang_isDeclaration(C.kind)) {
  5582. const Decl *D = cxcursor::getCursorDecl(C);
  5583. if (!D)
  5584. return SourceRange();
  5585. SourceRange R = D->getSourceRange();
  5586. // FIXME: Multiple variables declared in a single declaration
  5587. // currently lack the information needed to correctly determine their
  5588. // ranges when accounting for the type-specifier. We use context
  5589. // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
  5590. // and if so, whether it is the first decl.
  5591. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  5592. if (!cxcursor::isFirstInDeclGroup(C))
  5593. R.setBegin(VD->getLocation());
  5594. }
  5595. return R;
  5596. }
  5597. return SourceRange();
  5598. }
  5599. /// Retrieves the "raw" cursor extent, which is then extended to include
  5600. /// the decl-specifier-seq for declarations.
  5601. static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
  5602. if (clang_isDeclaration(C.kind)) {
  5603. const Decl *D = cxcursor::getCursorDecl(C);
  5604. if (!D)
  5605. return SourceRange();
  5606. SourceRange R = D->getSourceRange();
  5607. // Adjust the start of the location for declarations preceded by
  5608. // declaration specifiers.
  5609. SourceLocation StartLoc;
  5610. if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  5611. if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
  5612. StartLoc = TI->getTypeLoc().getBeginLoc();
  5613. } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
  5614. if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
  5615. StartLoc = TI->getTypeLoc().getBeginLoc();
  5616. }
  5617. if (StartLoc.isValid() && R.getBegin().isValid() &&
  5618. SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
  5619. R.setBegin(StartLoc);
  5620. // FIXME: Multiple variables declared in a single declaration
  5621. // currently lack the information needed to correctly determine their
  5622. // ranges when accounting for the type-specifier. We use context
  5623. // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
  5624. // and if so, whether it is the first decl.
  5625. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  5626. if (!cxcursor::isFirstInDeclGroup(C))
  5627. R.setBegin(VD->getLocation());
  5628. }
  5629. return R;
  5630. }
  5631. return getRawCursorExtent(C);
  5632. }
  5633. CXSourceRange clang_getCursorExtent(CXCursor C) {
  5634. SourceRange R = getRawCursorExtent(C);
  5635. if (R.isInvalid())
  5636. return clang_getNullRange();
  5637. return cxloc::translateSourceRange(getCursorContext(C), R);
  5638. }
  5639. CXCursor clang_getCursorReferenced(CXCursor C) {
  5640. if (clang_isInvalid(C.kind))
  5641. return clang_getNullCursor();
  5642. CXTranslationUnit tu = getCursorTU(C);
  5643. if (clang_isDeclaration(C.kind)) {
  5644. const Decl *D = getCursorDecl(C);
  5645. if (!D)
  5646. return clang_getNullCursor();
  5647. if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
  5648. return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
  5649. if (const ObjCPropertyImplDecl *PropImpl =
  5650. dyn_cast<ObjCPropertyImplDecl>(D))
  5651. if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
  5652. return MakeCXCursor(Property, tu);
  5653. return C;
  5654. }
  5655. if (clang_isExpression(C.kind)) {
  5656. const Expr *E = getCursorExpr(C);
  5657. const Decl *D = getDeclFromExpr(E);
  5658. if (D) {
  5659. CXCursor declCursor = MakeCXCursor(D, tu);
  5660. declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
  5661. declCursor);
  5662. return declCursor;
  5663. }
  5664. if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
  5665. return MakeCursorOverloadedDeclRef(Ovl, tu);
  5666. return clang_getNullCursor();
  5667. }
  5668. if (clang_isStatement(C.kind)) {
  5669. const Stmt *S = getCursorStmt(C);
  5670. if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
  5671. if (LabelDecl *label = Goto->getLabel())
  5672. if (LabelStmt *labelS = label->getStmt())
  5673. return MakeCXCursor(labelS, getCursorDecl(C), tu);
  5674. return clang_getNullCursor();
  5675. }
  5676. if (C.kind == CXCursor_MacroExpansion) {
  5677. if (const MacroDefinitionRecord *Def =
  5678. getCursorMacroExpansion(C).getDefinition())
  5679. return MakeMacroDefinitionCursor(Def, tu);
  5680. }
  5681. if (!clang_isReference(C.kind))
  5682. return clang_getNullCursor();
  5683. switch (C.kind) {
  5684. case CXCursor_ObjCSuperClassRef:
  5685. return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
  5686. case CXCursor_ObjCProtocolRef: {
  5687. const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
  5688. if (const ObjCProtocolDecl *Def = Prot->getDefinition())
  5689. return MakeCXCursor(Def, tu);
  5690. return MakeCXCursor(Prot, tu);
  5691. }
  5692. case CXCursor_ObjCClassRef: {
  5693. const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
  5694. if (const ObjCInterfaceDecl *Def = Class->getDefinition())
  5695. return MakeCXCursor(Def, tu);
  5696. return MakeCXCursor(Class, tu);
  5697. }
  5698. case CXCursor_TypeRef:
  5699. return MakeCXCursor(getCursorTypeRef(C).first, tu);
  5700. case CXCursor_TemplateRef:
  5701. return MakeCXCursor(getCursorTemplateRef(C).first, tu);
  5702. case CXCursor_NamespaceRef:
  5703. return MakeCXCursor(getCursorNamespaceRef(C).first, tu);
  5704. case CXCursor_MemberRef:
  5705. return MakeCXCursor(getCursorMemberRef(C).first, tu);
  5706. case CXCursor_CXXBaseSpecifier: {
  5707. const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
  5708. return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu));
  5709. }
  5710. case CXCursor_LabelRef:
  5711. // FIXME: We end up faking the "parent" declaration here because we
  5712. // don't want to make CXCursor larger.
  5713. return MakeCXCursor(
  5714. getCursorLabelRef(C).first,
  5715. cxtu::getASTUnit(tu)->getASTContext().getTranslationUnitDecl(), tu);
  5716. case CXCursor_OverloadedDeclRef:
  5717. return C;
  5718. case CXCursor_VariableRef:
  5719. return MakeCXCursor(getCursorVariableRef(C).first, tu);
  5720. default:
  5721. // We would prefer to enumerate all non-reference cursor kinds here.
  5722. llvm_unreachable("Unhandled reference cursor kind");
  5723. }
  5724. }
  5725. CXCursor clang_getCursorDefinition(CXCursor C) {
  5726. if (clang_isInvalid(C.kind))
  5727. return clang_getNullCursor();
  5728. CXTranslationUnit TU = getCursorTU(C);
  5729. bool WasReference = false;
  5730. if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
  5731. C = clang_getCursorReferenced(C);
  5732. WasReference = true;
  5733. }
  5734. if (C.kind == CXCursor_MacroExpansion)
  5735. return clang_getCursorReferenced(C);
  5736. if (!clang_isDeclaration(C.kind))
  5737. return clang_getNullCursor();
  5738. const Decl *D = getCursorDecl(C);
  5739. if (!D)
  5740. return clang_getNullCursor();
  5741. switch (D->getKind()) {
  5742. // Declaration kinds that don't really separate the notions of
  5743. // declaration and definition.
  5744. case Decl::Namespace:
  5745. case Decl::Typedef:
  5746. case Decl::TypeAlias:
  5747. case Decl::TypeAliasTemplate:
  5748. case Decl::TemplateTypeParm:
  5749. case Decl::EnumConstant:
  5750. case Decl::Field:
  5751. case Decl::Binding:
  5752. case Decl::MSProperty:
  5753. case Decl::MSGuid:
  5754. case Decl::HLSLBuffer:
  5755. case Decl::UnnamedGlobalConstant:
  5756. case Decl::TemplateParamObject:
  5757. case Decl::IndirectField:
  5758. case Decl::ObjCIvar:
  5759. case Decl::ObjCAtDefsField:
  5760. case Decl::ImplicitParam:
  5761. case Decl::ParmVar:
  5762. case Decl::NonTypeTemplateParm:
  5763. case Decl::TemplateTemplateParm:
  5764. case Decl::ObjCCategoryImpl:
  5765. case Decl::ObjCImplementation:
  5766. case Decl::AccessSpec:
  5767. case Decl::LinkageSpec:
  5768. case Decl::Export:
  5769. case Decl::ObjCPropertyImpl:
  5770. case Decl::FileScopeAsm:
  5771. case Decl::TopLevelStmt:
  5772. case Decl::StaticAssert:
  5773. case Decl::Block:
  5774. case Decl::Captured:
  5775. case Decl::OMPCapturedExpr:
  5776. case Decl::Label: // FIXME: Is this right??
  5777. case Decl::ClassScopeFunctionSpecialization:
  5778. case Decl::CXXDeductionGuide:
  5779. case Decl::Import:
  5780. case Decl::OMPThreadPrivate:
  5781. case Decl::OMPAllocate:
  5782. case Decl::OMPDeclareReduction:
  5783. case Decl::OMPDeclareMapper:
  5784. case Decl::OMPRequires:
  5785. case Decl::ObjCTypeParam:
  5786. case Decl::BuiltinTemplate:
  5787. case Decl::PragmaComment:
  5788. case Decl::PragmaDetectMismatch:
  5789. case Decl::UsingPack:
  5790. case Decl::Concept:
  5791. case Decl::ImplicitConceptSpecialization:
  5792. case Decl::LifetimeExtendedTemporary:
  5793. case Decl::RequiresExprBody:
  5794. case Decl::UnresolvedUsingIfExists:
  5795. return C;
  5796. // Declaration kinds that don't make any sense here, but are
  5797. // nonetheless harmless.
  5798. case Decl::Empty:
  5799. case Decl::TranslationUnit:
  5800. case Decl::ExternCContext:
  5801. break;
  5802. // Declaration kinds for which the definition is not resolvable.
  5803. case Decl::UnresolvedUsingTypename:
  5804. case Decl::UnresolvedUsingValue:
  5805. break;
  5806. case Decl::UsingDirective:
  5807. return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
  5808. TU);
  5809. case Decl::NamespaceAlias:
  5810. return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
  5811. case Decl::Enum:
  5812. case Decl::Record:
  5813. case Decl::CXXRecord:
  5814. case Decl::ClassTemplateSpecialization:
  5815. case Decl::ClassTemplatePartialSpecialization:
  5816. if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
  5817. return MakeCXCursor(Def, TU);
  5818. return clang_getNullCursor();
  5819. case Decl::Function:
  5820. case Decl::CXXMethod:
  5821. case Decl::CXXConstructor:
  5822. case Decl::CXXDestructor:
  5823. case Decl::CXXConversion: {
  5824. const FunctionDecl *Def = nullptr;
  5825. if (cast<FunctionDecl>(D)->getBody(Def))
  5826. return MakeCXCursor(Def, TU);
  5827. return clang_getNullCursor();
  5828. }
  5829. case Decl::Var:
  5830. case Decl::VarTemplateSpecialization:
  5831. case Decl::VarTemplatePartialSpecialization:
  5832. case Decl::Decomposition: {
  5833. // Ask the variable if it has a definition.
  5834. if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
  5835. return MakeCXCursor(Def, TU);
  5836. return clang_getNullCursor();
  5837. }
  5838. case Decl::FunctionTemplate: {
  5839. const FunctionDecl *Def = nullptr;
  5840. if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
  5841. return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
  5842. return clang_getNullCursor();
  5843. }
  5844. case Decl::ClassTemplate: {
  5845. if (RecordDecl *Def =
  5846. cast<ClassTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
  5847. return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
  5848. TU);
  5849. return clang_getNullCursor();
  5850. }
  5851. case Decl::VarTemplate: {
  5852. if (VarDecl *Def =
  5853. cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
  5854. return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
  5855. return clang_getNullCursor();
  5856. }
  5857. case Decl::Using:
  5858. case Decl::UsingEnum:
  5859. return MakeCursorOverloadedDeclRef(cast<BaseUsingDecl>(D), D->getLocation(),
  5860. TU);
  5861. case Decl::UsingShadow:
  5862. case Decl::ConstructorUsingShadow:
  5863. return clang_getCursorDefinition(
  5864. MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), TU));
  5865. case Decl::ObjCMethod: {
  5866. const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
  5867. if (Method->isThisDeclarationADefinition())
  5868. return C;
  5869. // Dig out the method definition in the associated
  5870. // @implementation, if we have it.
  5871. // FIXME: The ASTs should make finding the definition easier.
  5872. if (const ObjCInterfaceDecl *Class =
  5873. dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
  5874. if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
  5875. if (ObjCMethodDecl *Def = ClassImpl->getMethod(
  5876. Method->getSelector(), Method->isInstanceMethod()))
  5877. if (Def->isThisDeclarationADefinition())
  5878. return MakeCXCursor(Def, TU);
  5879. return clang_getNullCursor();
  5880. }
  5881. case Decl::ObjCCategory:
  5882. if (ObjCCategoryImplDecl *Impl =
  5883. cast<ObjCCategoryDecl>(D)->getImplementation())
  5884. return MakeCXCursor(Impl, TU);
  5885. return clang_getNullCursor();
  5886. case Decl::ObjCProtocol:
  5887. if (const ObjCProtocolDecl *Def =
  5888. cast<ObjCProtocolDecl>(D)->getDefinition())
  5889. return MakeCXCursor(Def, TU);
  5890. return clang_getNullCursor();
  5891. case Decl::ObjCInterface: {
  5892. // There are two notions of a "definition" for an Objective-C
  5893. // class: the interface and its implementation. When we resolved a
  5894. // reference to an Objective-C class, produce the @interface as
  5895. // the definition; when we were provided with the interface,
  5896. // produce the @implementation as the definition.
  5897. const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
  5898. if (WasReference) {
  5899. if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
  5900. return MakeCXCursor(Def, TU);
  5901. } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
  5902. return MakeCXCursor(Impl, TU);
  5903. return clang_getNullCursor();
  5904. }
  5905. case Decl::ObjCProperty:
  5906. // FIXME: We don't really know where to find the
  5907. // ObjCPropertyImplDecls that implement this property.
  5908. return clang_getNullCursor();
  5909. case Decl::ObjCCompatibleAlias:
  5910. if (const ObjCInterfaceDecl *Class =
  5911. cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
  5912. if (const ObjCInterfaceDecl *Def = Class->getDefinition())
  5913. return MakeCXCursor(Def, TU);
  5914. return clang_getNullCursor();
  5915. case Decl::Friend:
  5916. if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
  5917. return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
  5918. return clang_getNullCursor();
  5919. case Decl::FriendTemplate:
  5920. if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
  5921. return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
  5922. return clang_getNullCursor();
  5923. }
  5924. return clang_getNullCursor();
  5925. }
  5926. unsigned clang_isCursorDefinition(CXCursor C) {
  5927. if (!clang_isDeclaration(C.kind))
  5928. return 0;
  5929. return clang_getCursorDefinition(C) == C;
  5930. }
  5931. CXCursor clang_getCanonicalCursor(CXCursor C) {
  5932. if (!clang_isDeclaration(C.kind))
  5933. return C;
  5934. if (const Decl *D = getCursorDecl(C)) {
  5935. if (const ObjCCategoryImplDecl *CatImplD =
  5936. dyn_cast<ObjCCategoryImplDecl>(D))
  5937. if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
  5938. return MakeCXCursor(CatD, getCursorTU(C));
  5939. if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
  5940. if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
  5941. return MakeCXCursor(IFD, getCursorTU(C));
  5942. return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
  5943. }
  5944. return C;
  5945. }
  5946. int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
  5947. return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
  5948. }
  5949. unsigned clang_getNumOverloadedDecls(CXCursor C) {
  5950. if (C.kind != CXCursor_OverloadedDeclRef)
  5951. return 0;
  5952. OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
  5953. if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
  5954. return E->getNumDecls();
  5955. if (OverloadedTemplateStorage *S =
  5956. Storage.dyn_cast<OverloadedTemplateStorage *>())
  5957. return S->size();
  5958. const Decl *D = Storage.get<const Decl *>();
  5959. if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
  5960. return Using->shadow_size();
  5961. return 0;
  5962. }
  5963. CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
  5964. if (cursor.kind != CXCursor_OverloadedDeclRef)
  5965. return clang_getNullCursor();
  5966. if (index >= clang_getNumOverloadedDecls(cursor))
  5967. return clang_getNullCursor();
  5968. CXTranslationUnit TU = getCursorTU(cursor);
  5969. OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
  5970. if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
  5971. return MakeCXCursor(E->decls_begin()[index], TU);
  5972. if (OverloadedTemplateStorage *S =
  5973. Storage.dyn_cast<OverloadedTemplateStorage *>())
  5974. return MakeCXCursor(S->begin()[index], TU);
  5975. const Decl *D = Storage.get<const Decl *>();
  5976. if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
  5977. // FIXME: This is, unfortunately, linear time.
  5978. UsingDecl::shadow_iterator Pos = Using->shadow_begin();
  5979. std::advance(Pos, index);
  5980. return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
  5981. }
  5982. return clang_getNullCursor();
  5983. }
  5984. void clang_getDefinitionSpellingAndExtent(
  5985. CXCursor C, const char **startBuf, const char **endBuf, unsigned *startLine,
  5986. unsigned *startColumn, unsigned *endLine, unsigned *endColumn) {
  5987. assert(getCursorDecl(C) && "CXCursor has null decl");
  5988. const auto *FD = cast<FunctionDecl>(getCursorDecl(C));
  5989. const auto *Body = cast<CompoundStmt>(FD->getBody());
  5990. SourceManager &SM = FD->getASTContext().getSourceManager();
  5991. *startBuf = SM.getCharacterData(Body->getLBracLoc());
  5992. *endBuf = SM.getCharacterData(Body->getRBracLoc());
  5993. *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
  5994. *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
  5995. *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
  5996. *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
  5997. }
  5998. CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
  5999. unsigned PieceIndex) {
  6000. RefNamePieces Pieces;
  6001. switch (C.kind) {
  6002. case CXCursor_MemberRefExpr:
  6003. if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
  6004. Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
  6005. E->getQualifierLoc().getSourceRange());
  6006. break;
  6007. case CXCursor_DeclRefExpr:
  6008. if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
  6009. SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
  6010. Pieces =
  6011. buildPieces(NameFlags, false, E->getNameInfo(),
  6012. E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
  6013. }
  6014. break;
  6015. case CXCursor_CallExpr:
  6016. if (const CXXOperatorCallExpr *OCE =
  6017. dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
  6018. const Expr *Callee = OCE->getCallee();
  6019. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
  6020. Callee = ICE->getSubExpr();
  6021. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
  6022. Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
  6023. DRE->getQualifierLoc().getSourceRange());
  6024. }
  6025. break;
  6026. default:
  6027. break;
  6028. }
  6029. if (Pieces.empty()) {
  6030. if (PieceIndex == 0)
  6031. return clang_getCursorExtent(C);
  6032. } else if (PieceIndex < Pieces.size()) {
  6033. SourceRange R = Pieces[PieceIndex];
  6034. if (R.isValid())
  6035. return cxloc::translateSourceRange(getCursorContext(C), R);
  6036. }
  6037. return clang_getNullRange();
  6038. }
  6039. void clang_enableStackTraces(void) {
  6040. // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
  6041. llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
  6042. }
  6043. void clang_executeOnThread(void (*fn)(void *), void *user_data,
  6044. unsigned stack_size) {
  6045. llvm::thread Thread(stack_size == 0 ? clang::DesiredStackSize
  6046. : std::optional<unsigned>(stack_size),
  6047. fn, user_data);
  6048. Thread.join();
  6049. }
  6050. //===----------------------------------------------------------------------===//
  6051. // Token-based Operations.
  6052. //===----------------------------------------------------------------------===//
  6053. /* CXToken layout:
  6054. * int_data[0]: a CXTokenKind
  6055. * int_data[1]: starting token location
  6056. * int_data[2]: token length
  6057. * int_data[3]: reserved
  6058. * ptr_data: for identifiers and keywords, an IdentifierInfo*.
  6059. * otherwise unused.
  6060. */
  6061. CXTokenKind clang_getTokenKind(CXToken CXTok) {
  6062. return static_cast<CXTokenKind>(CXTok.int_data[0]);
  6063. }
  6064. CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
  6065. switch (clang_getTokenKind(CXTok)) {
  6066. case CXToken_Identifier:
  6067. case CXToken_Keyword:
  6068. // We know we have an IdentifierInfo*, so use that.
  6069. return cxstring::createRef(
  6070. static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
  6071. case CXToken_Literal: {
  6072. // We have stashed the starting pointer in the ptr_data field. Use it.
  6073. const char *Text = static_cast<const char *>(CXTok.ptr_data);
  6074. return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
  6075. }
  6076. case CXToken_Punctuation:
  6077. case CXToken_Comment:
  6078. break;
  6079. }
  6080. if (isNotUsableTU(TU)) {
  6081. LOG_BAD_TU(TU);
  6082. return cxstring::createEmpty();
  6083. }
  6084. // We have to find the starting buffer pointer the hard way, by
  6085. // deconstructing the source location.
  6086. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6087. if (!CXXUnit)
  6088. return cxstring::createEmpty();
  6089. SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
  6090. std::pair<FileID, unsigned> LocInfo =
  6091. CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
  6092. bool Invalid = false;
  6093. StringRef Buffer =
  6094. CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
  6095. if (Invalid)
  6096. return cxstring::createEmpty();
  6097. return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
  6098. }
  6099. CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
  6100. if (isNotUsableTU(TU)) {
  6101. LOG_BAD_TU(TU);
  6102. return clang_getNullLocation();
  6103. }
  6104. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6105. if (!CXXUnit)
  6106. return clang_getNullLocation();
  6107. return cxloc::translateSourceLocation(
  6108. CXXUnit->getASTContext(),
  6109. SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
  6110. }
  6111. CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
  6112. if (isNotUsableTU(TU)) {
  6113. LOG_BAD_TU(TU);
  6114. return clang_getNullRange();
  6115. }
  6116. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6117. if (!CXXUnit)
  6118. return clang_getNullRange();
  6119. return cxloc::translateSourceRange(
  6120. CXXUnit->getASTContext(),
  6121. SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
  6122. }
  6123. static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
  6124. SmallVectorImpl<CXToken> &CXTokens) {
  6125. SourceManager &SourceMgr = CXXUnit->getSourceManager();
  6126. std::pair<FileID, unsigned> BeginLocInfo =
  6127. SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
  6128. std::pair<FileID, unsigned> EndLocInfo =
  6129. SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
  6130. // Cannot tokenize across files.
  6131. if (BeginLocInfo.first != EndLocInfo.first)
  6132. return;
  6133. // Create a lexer
  6134. bool Invalid = false;
  6135. StringRef Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
  6136. if (Invalid)
  6137. return;
  6138. Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
  6139. CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
  6140. Buffer.data() + BeginLocInfo.second, Buffer.end());
  6141. Lex.SetCommentRetentionState(true);
  6142. // Lex tokens until we hit the end of the range.
  6143. const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
  6144. Token Tok;
  6145. bool previousWasAt = false;
  6146. do {
  6147. // Lex the next token
  6148. Lex.LexFromRawLexer(Tok);
  6149. if (Tok.is(tok::eof))
  6150. break;
  6151. // Initialize the CXToken.
  6152. CXToken CXTok;
  6153. // - Common fields
  6154. CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
  6155. CXTok.int_data[2] = Tok.getLength();
  6156. CXTok.int_data[3] = 0;
  6157. // - Kind-specific fields
  6158. if (Tok.isLiteral()) {
  6159. CXTok.int_data[0] = CXToken_Literal;
  6160. CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
  6161. } else if (Tok.is(tok::raw_identifier)) {
  6162. // Lookup the identifier to determine whether we have a keyword.
  6163. IdentifierInfo *II = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
  6164. if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
  6165. CXTok.int_data[0] = CXToken_Keyword;
  6166. } else {
  6167. CXTok.int_data[0] =
  6168. Tok.is(tok::identifier) ? CXToken_Identifier : CXToken_Keyword;
  6169. }
  6170. CXTok.ptr_data = II;
  6171. } else if (Tok.is(tok::comment)) {
  6172. CXTok.int_data[0] = CXToken_Comment;
  6173. CXTok.ptr_data = nullptr;
  6174. } else {
  6175. CXTok.int_data[0] = CXToken_Punctuation;
  6176. CXTok.ptr_data = nullptr;
  6177. }
  6178. CXTokens.push_back(CXTok);
  6179. previousWasAt = Tok.is(tok::at);
  6180. } while (Lex.getBufferLocation() < EffectiveBufferEnd);
  6181. }
  6182. CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
  6183. LOG_FUNC_SECTION { *Log << TU << ' ' << Location; }
  6184. if (isNotUsableTU(TU)) {
  6185. LOG_BAD_TU(TU);
  6186. return nullptr;
  6187. }
  6188. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6189. if (!CXXUnit)
  6190. return nullptr;
  6191. SourceLocation Begin = cxloc::translateSourceLocation(Location);
  6192. if (Begin.isInvalid())
  6193. return nullptr;
  6194. SourceManager &SM = CXXUnit->getSourceManager();
  6195. std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
  6196. DecomposedEnd.second +=
  6197. Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
  6198. SourceLocation End =
  6199. SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
  6200. SmallVector<CXToken, 32> CXTokens;
  6201. getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
  6202. if (CXTokens.empty())
  6203. return nullptr;
  6204. CXTokens.resize(1);
  6205. CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
  6206. memmove(Token, CXTokens.data(), sizeof(CXToken));
  6207. return Token;
  6208. }
  6209. void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens,
  6210. unsigned *NumTokens) {
  6211. LOG_FUNC_SECTION { *Log << TU << ' ' << Range; }
  6212. if (Tokens)
  6213. *Tokens = nullptr;
  6214. if (NumTokens)
  6215. *NumTokens = 0;
  6216. if (isNotUsableTU(TU)) {
  6217. LOG_BAD_TU(TU);
  6218. return;
  6219. }
  6220. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6221. if (!CXXUnit || !Tokens || !NumTokens)
  6222. return;
  6223. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  6224. SourceRange R = cxloc::translateCXSourceRange(Range);
  6225. if (R.isInvalid())
  6226. return;
  6227. SmallVector<CXToken, 32> CXTokens;
  6228. getTokens(CXXUnit, R, CXTokens);
  6229. if (CXTokens.empty())
  6230. return;
  6231. *Tokens = static_cast<CXToken *>(
  6232. llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
  6233. memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
  6234. *NumTokens = CXTokens.size();
  6235. }
  6236. void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens,
  6237. unsigned NumTokens) {
  6238. free(Tokens);
  6239. }
  6240. //===----------------------------------------------------------------------===//
  6241. // Token annotation APIs.
  6242. //===----------------------------------------------------------------------===//
  6243. static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
  6244. CXCursor parent,
  6245. CXClientData client_data);
  6246. static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
  6247. CXClientData client_data);
  6248. namespace {
  6249. class AnnotateTokensWorker {
  6250. CXToken *Tokens;
  6251. CXCursor *Cursors;
  6252. unsigned NumTokens;
  6253. unsigned TokIdx;
  6254. unsigned PreprocessingTokIdx;
  6255. CursorVisitor AnnotateVis;
  6256. SourceManager &SrcMgr;
  6257. bool HasContextSensitiveKeywords;
  6258. struct PostChildrenAction {
  6259. CXCursor cursor;
  6260. enum Action { Invalid, Ignore, Postpone } action;
  6261. };
  6262. using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
  6263. struct PostChildrenInfo {
  6264. CXCursor Cursor;
  6265. SourceRange CursorRange;
  6266. unsigned BeforeReachingCursorIdx;
  6267. unsigned BeforeChildrenTokenIdx;
  6268. PostChildrenActions ChildActions;
  6269. };
  6270. SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
  6271. CXToken &getTok(unsigned Idx) {
  6272. assert(Idx < NumTokens);
  6273. return Tokens[Idx];
  6274. }
  6275. const CXToken &getTok(unsigned Idx) const {
  6276. assert(Idx < NumTokens);
  6277. return Tokens[Idx];
  6278. }
  6279. bool MoreTokens() const { return TokIdx < NumTokens; }
  6280. unsigned NextToken() const { return TokIdx; }
  6281. void AdvanceToken() { ++TokIdx; }
  6282. SourceLocation GetTokenLoc(unsigned tokI) {
  6283. return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
  6284. }
  6285. bool isFunctionMacroToken(unsigned tokI) const {
  6286. return getTok(tokI).int_data[3] != 0;
  6287. }
  6288. SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
  6289. return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
  6290. }
  6291. void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
  6292. bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
  6293. SourceRange);
  6294. public:
  6295. AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
  6296. CXTranslationUnit TU, SourceRange RegionOfInterest)
  6297. : Tokens(tokens), Cursors(cursors), NumTokens(numTokens), TokIdx(0),
  6298. PreprocessingTokIdx(0),
  6299. AnnotateVis(TU, AnnotateTokensVisitor, this,
  6300. /*VisitPreprocessorLast=*/true,
  6301. /*VisitIncludedEntities=*/false, RegionOfInterest,
  6302. /*VisitDeclsOnly=*/false,
  6303. AnnotateTokensPostChildrenVisitor),
  6304. SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
  6305. HasContextSensitiveKeywords(false) {}
  6306. void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
  6307. enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
  6308. bool IsIgnoredChildCursor(CXCursor cursor) const;
  6309. PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
  6310. bool postVisitChildren(CXCursor cursor);
  6311. void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
  6312. void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
  6313. void AnnotateTokens();
  6314. /// Determine whether the annotator saw any cursors that have
  6315. /// context-sensitive keywords.
  6316. bool hasContextSensitiveKeywords() const {
  6317. return HasContextSensitiveKeywords;
  6318. }
  6319. ~AnnotateTokensWorker() { assert(PostChildrenInfos.empty()); }
  6320. };
  6321. } // namespace
  6322. void AnnotateTokensWorker::AnnotateTokens() {
  6323. // Walk the AST within the region of interest, annotating tokens
  6324. // along the way.
  6325. AnnotateVis.visitFileRegion();
  6326. }
  6327. bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
  6328. if (PostChildrenInfos.empty())
  6329. return false;
  6330. for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
  6331. if (ChildAction.cursor == cursor &&
  6332. ChildAction.action == PostChildrenAction::Ignore) {
  6333. return true;
  6334. }
  6335. }
  6336. return false;
  6337. }
  6338. const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
  6339. if (!clang_isExpression(Cursor.kind))
  6340. return nullptr;
  6341. const Expr *E = getCursorExpr(Cursor);
  6342. if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  6343. const OverloadedOperatorKind Kind = OCE->getOperator();
  6344. if (Kind == OO_Call || Kind == OO_Subscript)
  6345. return OCE;
  6346. }
  6347. return nullptr;
  6348. }
  6349. AnnotateTokensWorker::PostChildrenActions
  6350. AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
  6351. PostChildrenActions actions;
  6352. // The DeclRefExpr of CXXOperatorCallExpr referring to the custom operator is
  6353. // visited before the arguments to the operator call. For the Call and
  6354. // Subscript operator the range of this DeclRefExpr includes the whole call
  6355. // expression, so that all tokens in that range would be mapped to the
  6356. // operator function, including the tokens of the arguments. To avoid that,
  6357. // ensure to visit this DeclRefExpr as last node.
  6358. if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
  6359. const Expr *Callee = OCE->getCallee();
  6360. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
  6361. const Expr *SubExpr = ICE->getSubExpr();
  6362. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
  6363. const Decl *parentDecl = getCursorDecl(Cursor);
  6364. CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
  6365. // Visit the DeclRefExpr as last.
  6366. CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
  6367. actions.push_back({cxChild, PostChildrenAction::Postpone});
  6368. // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
  6369. // wide range as the DeclRefExpr. We can skip visiting this entirely.
  6370. cxChild = MakeCXCursor(ICE, parentDecl, TU);
  6371. actions.push_back({cxChild, PostChildrenAction::Ignore});
  6372. }
  6373. }
  6374. }
  6375. return actions;
  6376. }
  6377. static inline void updateCursorAnnotation(CXCursor &Cursor,
  6378. const CXCursor &updateC) {
  6379. if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
  6380. return;
  6381. Cursor = updateC;
  6382. }
  6383. /// It annotates and advances tokens with a cursor until the comparison
  6384. //// between the cursor location and the source range is the same as
  6385. /// \arg compResult.
  6386. ///
  6387. /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
  6388. /// Pass RangeOverlap to annotate tokens inside a range.
  6389. void AnnotateTokensWorker::annotateAndAdvanceTokens(
  6390. CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
  6391. while (MoreTokens()) {
  6392. const unsigned I = NextToken();
  6393. if (isFunctionMacroToken(I))
  6394. if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
  6395. return;
  6396. SourceLocation TokLoc = GetTokenLoc(I);
  6397. if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
  6398. updateCursorAnnotation(Cursors[I], updateC);
  6399. AdvanceToken();
  6400. continue;
  6401. }
  6402. break;
  6403. }
  6404. }
  6405. /// Special annotation handling for macro argument tokens.
  6406. /// \returns true if it advanced beyond all macro tokens, false otherwise.
  6407. bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
  6408. CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
  6409. assert(MoreTokens());
  6410. assert(isFunctionMacroToken(NextToken()) &&
  6411. "Should be called only for macro arg tokens");
  6412. // This works differently than annotateAndAdvanceTokens; because expanded
  6413. // macro arguments can have arbitrary translation-unit source order, we do not
  6414. // advance the token index one by one until a token fails the range test.
  6415. // We only advance once past all of the macro arg tokens if all of them
  6416. // pass the range test. If one of them fails we keep the token index pointing
  6417. // at the start of the macro arg tokens so that the failing token will be
  6418. // annotated by a subsequent annotation try.
  6419. bool atLeastOneCompFail = false;
  6420. unsigned I = NextToken();
  6421. for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
  6422. SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
  6423. if (TokLoc.isFileID())
  6424. continue; // not macro arg token, it's parens or comma.
  6425. if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
  6426. if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
  6427. Cursors[I] = updateC;
  6428. } else
  6429. atLeastOneCompFail = true;
  6430. }
  6431. if (atLeastOneCompFail)
  6432. return false;
  6433. TokIdx = I; // All of the tokens were handled, advance beyond all of them.
  6434. return true;
  6435. }
  6436. enum CXChildVisitResult AnnotateTokensWorker::Visit(CXCursor cursor,
  6437. CXCursor parent) {
  6438. SourceRange cursorRange = getRawCursorExtent(cursor);
  6439. if (cursorRange.isInvalid())
  6440. return CXChildVisit_Recurse;
  6441. if (IsIgnoredChildCursor(cursor))
  6442. return CXChildVisit_Continue;
  6443. if (!HasContextSensitiveKeywords) {
  6444. // Objective-C properties can have context-sensitive keywords.
  6445. if (cursor.kind == CXCursor_ObjCPropertyDecl) {
  6446. if (const ObjCPropertyDecl *Property =
  6447. dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
  6448. HasContextSensitiveKeywords =
  6449. Property->getPropertyAttributesAsWritten() != 0;
  6450. }
  6451. // Objective-C methods can have context-sensitive keywords.
  6452. else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
  6453. cursor.kind == CXCursor_ObjCClassMethodDecl) {
  6454. if (const ObjCMethodDecl *Method =
  6455. dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
  6456. if (Method->getObjCDeclQualifier())
  6457. HasContextSensitiveKeywords = true;
  6458. else {
  6459. for (const auto *P : Method->parameters()) {
  6460. if (P->getObjCDeclQualifier()) {
  6461. HasContextSensitiveKeywords = true;
  6462. break;
  6463. }
  6464. }
  6465. }
  6466. }
  6467. }
  6468. // C++ methods can have context-sensitive keywords.
  6469. else if (cursor.kind == CXCursor_CXXMethod) {
  6470. if (const CXXMethodDecl *Method =
  6471. dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
  6472. if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
  6473. HasContextSensitiveKeywords = true;
  6474. }
  6475. }
  6476. // C++ classes can have context-sensitive keywords.
  6477. else if (cursor.kind == CXCursor_StructDecl ||
  6478. cursor.kind == CXCursor_ClassDecl ||
  6479. cursor.kind == CXCursor_ClassTemplate ||
  6480. cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
  6481. if (const Decl *D = getCursorDecl(cursor))
  6482. if (D->hasAttr<FinalAttr>())
  6483. HasContextSensitiveKeywords = true;
  6484. }
  6485. }
  6486. // Don't override a property annotation with its getter/setter method.
  6487. if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
  6488. parent.kind == CXCursor_ObjCPropertyDecl)
  6489. return CXChildVisit_Continue;
  6490. if (clang_isPreprocessing(cursor.kind)) {
  6491. // Items in the preprocessing record are kept separate from items in
  6492. // declarations, so we keep a separate token index.
  6493. unsigned SavedTokIdx = TokIdx;
  6494. TokIdx = PreprocessingTokIdx;
  6495. // Skip tokens up until we catch up to the beginning of the preprocessing
  6496. // entry.
  6497. while (MoreTokens()) {
  6498. const unsigned I = NextToken();
  6499. SourceLocation TokLoc = GetTokenLoc(I);
  6500. switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
  6501. case RangeBefore:
  6502. AdvanceToken();
  6503. continue;
  6504. case RangeAfter:
  6505. case RangeOverlap:
  6506. break;
  6507. }
  6508. break;
  6509. }
  6510. // Look at all of the tokens within this range.
  6511. while (MoreTokens()) {
  6512. const unsigned I = NextToken();
  6513. SourceLocation TokLoc = GetTokenLoc(I);
  6514. switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
  6515. case RangeBefore:
  6516. llvm_unreachable("Infeasible");
  6517. case RangeAfter:
  6518. break;
  6519. case RangeOverlap:
  6520. // For macro expansions, just note where the beginning of the macro
  6521. // expansion occurs.
  6522. if (cursor.kind == CXCursor_MacroExpansion) {
  6523. if (TokLoc == cursorRange.getBegin())
  6524. Cursors[I] = cursor;
  6525. AdvanceToken();
  6526. break;
  6527. }
  6528. // We may have already annotated macro names inside macro definitions.
  6529. if (Cursors[I].kind != CXCursor_MacroExpansion)
  6530. Cursors[I] = cursor;
  6531. AdvanceToken();
  6532. continue;
  6533. }
  6534. break;
  6535. }
  6536. // Save the preprocessing token index; restore the non-preprocessing
  6537. // token index.
  6538. PreprocessingTokIdx = TokIdx;
  6539. TokIdx = SavedTokIdx;
  6540. return CXChildVisit_Recurse;
  6541. }
  6542. if (cursorRange.isInvalid())
  6543. return CXChildVisit_Continue;
  6544. unsigned BeforeReachingCursorIdx = NextToken();
  6545. const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
  6546. const enum CXCursorKind K = clang_getCursorKind(parent);
  6547. const CXCursor updateC =
  6548. (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
  6549. // Attributes are annotated out-of-order, skip tokens until we reach it.
  6550. clang_isAttribute(cursor.kind))
  6551. ? clang_getNullCursor()
  6552. : parent;
  6553. annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
  6554. // Avoid having the cursor of an expression "overwrite" the annotation of the
  6555. // variable declaration that it belongs to.
  6556. // This can happen for C++ constructor expressions whose range generally
  6557. // include the variable declaration, e.g.:
  6558. // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
  6559. if (clang_isExpression(cursorK) && MoreTokens()) {
  6560. const Expr *E = getCursorExpr(cursor);
  6561. if (const Decl *D = getCursorDecl(cursor)) {
  6562. const unsigned I = NextToken();
  6563. if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
  6564. E->getBeginLoc() == D->getLocation() &&
  6565. E->getBeginLoc() == GetTokenLoc(I)) {
  6566. updateCursorAnnotation(Cursors[I], updateC);
  6567. AdvanceToken();
  6568. }
  6569. }
  6570. }
  6571. // Before recursing into the children keep some state that we are going
  6572. // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
  6573. // extra work after the child nodes are visited.
  6574. // Note that we don't call VisitChildren here to avoid traversing statements
  6575. // code-recursively which can blow the stack.
  6576. PostChildrenInfo Info;
  6577. Info.Cursor = cursor;
  6578. Info.CursorRange = cursorRange;
  6579. Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
  6580. Info.BeforeChildrenTokenIdx = NextToken();
  6581. Info.ChildActions = DetermineChildActions(cursor);
  6582. PostChildrenInfos.push_back(Info);
  6583. return CXChildVisit_Recurse;
  6584. }
  6585. bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
  6586. if (PostChildrenInfos.empty())
  6587. return false;
  6588. const PostChildrenInfo &Info = PostChildrenInfos.back();
  6589. if (!clang_equalCursors(Info.Cursor, cursor))
  6590. return false;
  6591. HandlePostPonedChildCursors(Info);
  6592. const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
  6593. const unsigned AfterChildren = NextToken();
  6594. SourceRange cursorRange = Info.CursorRange;
  6595. // Scan the tokens that are at the end of the cursor, but are not captured
  6596. // but the child cursors.
  6597. annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
  6598. // Scan the tokens that are at the beginning of the cursor, but are not
  6599. // capture by the child cursors.
  6600. for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
  6601. if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
  6602. break;
  6603. Cursors[I] = cursor;
  6604. }
  6605. // Attributes are annotated out-of-order, rewind TokIdx to when we first
  6606. // encountered the attribute cursor.
  6607. if (clang_isAttribute(cursor.kind))
  6608. TokIdx = Info.BeforeReachingCursorIdx;
  6609. PostChildrenInfos.pop_back();
  6610. return false;
  6611. }
  6612. void AnnotateTokensWorker::HandlePostPonedChildCursors(
  6613. const PostChildrenInfo &Info) {
  6614. for (const auto &ChildAction : Info.ChildActions) {
  6615. if (ChildAction.action == PostChildrenAction::Postpone) {
  6616. HandlePostPonedChildCursor(ChildAction.cursor,
  6617. Info.BeforeChildrenTokenIdx);
  6618. }
  6619. }
  6620. }
  6621. void AnnotateTokensWorker::HandlePostPonedChildCursor(
  6622. CXCursor Cursor, unsigned StartTokenIndex) {
  6623. unsigned I = StartTokenIndex;
  6624. // The bracket tokens of a Call or Subscript operator are mapped to
  6625. // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
  6626. // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
  6627. for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
  6628. const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
  6629. Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
  6630. if (clang_Range_isNull(CXRefNameRange))
  6631. break; // All ranges handled.
  6632. SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
  6633. while (I < NumTokens) {
  6634. const SourceLocation TokenLocation = GetTokenLoc(I);
  6635. if (!TokenLocation.isValid())
  6636. break;
  6637. // Adapt the end range, because LocationCompare() reports
  6638. // RangeOverlap even for the not-inclusive end location.
  6639. const SourceLocation fixedEnd =
  6640. RefNameRange.getEnd().getLocWithOffset(-1);
  6641. RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
  6642. const RangeComparisonResult ComparisonResult =
  6643. LocationCompare(SrcMgr, TokenLocation, RefNameRange);
  6644. if (ComparisonResult == RangeOverlap) {
  6645. Cursors[I++] = Cursor;
  6646. } else if (ComparisonResult == RangeBefore) {
  6647. ++I; // Not relevant token, check next one.
  6648. } else if (ComparisonResult == RangeAfter) {
  6649. break; // All tokens updated for current range, check next.
  6650. }
  6651. }
  6652. }
  6653. }
  6654. static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
  6655. CXCursor parent,
  6656. CXClientData client_data) {
  6657. return static_cast<AnnotateTokensWorker *>(client_data)
  6658. ->Visit(cursor, parent);
  6659. }
  6660. static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
  6661. CXClientData client_data) {
  6662. return static_cast<AnnotateTokensWorker *>(client_data)
  6663. ->postVisitChildren(cursor);
  6664. }
  6665. namespace {
  6666. /// Uses the macro expansions in the preprocessing record to find
  6667. /// and mark tokens that are macro arguments. This info is used by the
  6668. /// AnnotateTokensWorker.
  6669. class MarkMacroArgTokensVisitor {
  6670. SourceManager &SM;
  6671. CXToken *Tokens;
  6672. unsigned NumTokens;
  6673. unsigned CurIdx;
  6674. public:
  6675. MarkMacroArgTokensVisitor(SourceManager &SM, CXToken *tokens,
  6676. unsigned numTokens)
  6677. : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) {}
  6678. CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
  6679. if (cursor.kind != CXCursor_MacroExpansion)
  6680. return CXChildVisit_Continue;
  6681. SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
  6682. if (macroRange.getBegin() == macroRange.getEnd())
  6683. return CXChildVisit_Continue; // it's not a function macro.
  6684. for (; CurIdx < NumTokens; ++CurIdx) {
  6685. if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
  6686. macroRange.getBegin()))
  6687. break;
  6688. }
  6689. if (CurIdx == NumTokens)
  6690. return CXChildVisit_Break;
  6691. for (; CurIdx < NumTokens; ++CurIdx) {
  6692. SourceLocation tokLoc = getTokenLoc(CurIdx);
  6693. if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
  6694. break;
  6695. setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
  6696. }
  6697. if (CurIdx == NumTokens)
  6698. return CXChildVisit_Break;
  6699. return CXChildVisit_Continue;
  6700. }
  6701. private:
  6702. CXToken &getTok(unsigned Idx) {
  6703. assert(Idx < NumTokens);
  6704. return Tokens[Idx];
  6705. }
  6706. const CXToken &getTok(unsigned Idx) const {
  6707. assert(Idx < NumTokens);
  6708. return Tokens[Idx];
  6709. }
  6710. SourceLocation getTokenLoc(unsigned tokI) {
  6711. return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
  6712. }
  6713. void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
  6714. // The third field is reserved and currently not used. Use it here
  6715. // to mark macro arg expanded tokens with their expanded locations.
  6716. getTok(tokI).int_data[3] = loc.getRawEncoding();
  6717. }
  6718. };
  6719. } // end anonymous namespace
  6720. static CXChildVisitResult
  6721. MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
  6722. CXClientData client_data) {
  6723. return static_cast<MarkMacroArgTokensVisitor *>(client_data)
  6724. ->visit(cursor, parent);
  6725. }
  6726. /// Used by \c annotatePreprocessorTokens.
  6727. /// \returns true if lexing was finished, false otherwise.
  6728. static bool lexNext(Lexer &Lex, Token &Tok, unsigned &NextIdx,
  6729. unsigned NumTokens) {
  6730. if (NextIdx >= NumTokens)
  6731. return true;
  6732. ++NextIdx;
  6733. Lex.LexFromRawLexer(Tok);
  6734. return Tok.is(tok::eof);
  6735. }
  6736. static void annotatePreprocessorTokens(CXTranslationUnit TU,
  6737. SourceRange RegionOfInterest,
  6738. CXCursor *Cursors, CXToken *Tokens,
  6739. unsigned NumTokens) {
  6740. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6741. Preprocessor &PP = CXXUnit->getPreprocessor();
  6742. SourceManager &SourceMgr = CXXUnit->getSourceManager();
  6743. std::pair<FileID, unsigned> BeginLocInfo =
  6744. SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
  6745. std::pair<FileID, unsigned> EndLocInfo =
  6746. SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
  6747. if (BeginLocInfo.first != EndLocInfo.first)
  6748. return;
  6749. StringRef Buffer;
  6750. bool Invalid = false;
  6751. Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
  6752. if (Buffer.empty() || Invalid)
  6753. return;
  6754. Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
  6755. CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
  6756. Buffer.data() + BeginLocInfo.second, Buffer.end());
  6757. Lex.SetCommentRetentionState(true);
  6758. unsigned NextIdx = 0;
  6759. // Lex tokens in raw mode until we hit the end of the range, to avoid
  6760. // entering #includes or expanding macros.
  6761. while (true) {
  6762. Token Tok;
  6763. if (lexNext(Lex, Tok, NextIdx, NumTokens))
  6764. break;
  6765. unsigned TokIdx = NextIdx - 1;
  6766. assert(Tok.getLocation() ==
  6767. SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
  6768. reprocess:
  6769. if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
  6770. // We have found a preprocessing directive. Annotate the tokens
  6771. // appropriately.
  6772. //
  6773. // FIXME: Some simple tests here could identify macro definitions and
  6774. // #undefs, to provide specific cursor kinds for those.
  6775. SourceLocation BeginLoc = Tok.getLocation();
  6776. if (lexNext(Lex, Tok, NextIdx, NumTokens))
  6777. break;
  6778. MacroInfo *MI = nullptr;
  6779. if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
  6780. if (lexNext(Lex, Tok, NextIdx, NumTokens))
  6781. break;
  6782. if (Tok.is(tok::raw_identifier)) {
  6783. IdentifierInfo &II =
  6784. PP.getIdentifierTable().get(Tok.getRawIdentifier());
  6785. SourceLocation MappedTokLoc =
  6786. CXXUnit->mapLocationToPreamble(Tok.getLocation());
  6787. MI = getMacroInfo(II, MappedTokLoc, TU);
  6788. }
  6789. }
  6790. bool finished = false;
  6791. do {
  6792. if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
  6793. finished = true;
  6794. break;
  6795. }
  6796. // If we are in a macro definition, check if the token was ever a
  6797. // macro name and annotate it if that's the case.
  6798. if (MI) {
  6799. SourceLocation SaveLoc = Tok.getLocation();
  6800. Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
  6801. MacroDefinitionRecord *MacroDef =
  6802. checkForMacroInMacroDefinition(MI, Tok, TU);
  6803. Tok.setLocation(SaveLoc);
  6804. if (MacroDef)
  6805. Cursors[NextIdx - 1] =
  6806. MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
  6807. }
  6808. } while (!Tok.isAtStartOfLine());
  6809. unsigned LastIdx = finished ? NextIdx - 1 : NextIdx - 2;
  6810. assert(TokIdx <= LastIdx);
  6811. SourceLocation EndLoc =
  6812. SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
  6813. CXCursor Cursor =
  6814. MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
  6815. for (; TokIdx <= LastIdx; ++TokIdx)
  6816. updateCursorAnnotation(Cursors[TokIdx], Cursor);
  6817. if (finished)
  6818. break;
  6819. goto reprocess;
  6820. }
  6821. }
  6822. }
  6823. // This gets run a separate thread to avoid stack blowout.
  6824. static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
  6825. CXToken *Tokens, unsigned NumTokens,
  6826. CXCursor *Cursors) {
  6827. CIndexer *CXXIdx = TU->CIdx;
  6828. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
  6829. setThreadBackgroundPriority();
  6830. // Determine the region of interest, which contains all of the tokens.
  6831. SourceRange RegionOfInterest;
  6832. RegionOfInterest.setBegin(
  6833. cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
  6834. RegionOfInterest.setEnd(cxloc::translateSourceLocation(
  6835. clang_getTokenLocation(TU, Tokens[NumTokens - 1])));
  6836. // Relex the tokens within the source range to look for preprocessing
  6837. // directives.
  6838. annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
  6839. // If begin location points inside a macro argument, set it to the expansion
  6840. // location so we can have the full context when annotating semantically.
  6841. {
  6842. SourceManager &SM = CXXUnit->getSourceManager();
  6843. SourceLocation Loc =
  6844. SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
  6845. if (Loc.isMacroID())
  6846. RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
  6847. }
  6848. if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
  6849. // Search and mark tokens that are macro argument expansions.
  6850. MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), Tokens,
  6851. NumTokens);
  6852. CursorVisitor MacroArgMarker(
  6853. TU, MarkMacroArgTokensVisitorDelegate, &Visitor,
  6854. /*VisitPreprocessorLast=*/true,
  6855. /*VisitIncludedEntities=*/false, RegionOfInterest);
  6856. MacroArgMarker.visitPreprocessedEntitiesInRegion();
  6857. }
  6858. // Annotate all of the source locations in the region of interest that map to
  6859. // a specific cursor.
  6860. AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
  6861. // FIXME: We use a ridiculous stack size here because the data-recursion
  6862. // algorithm uses a large stack frame than the non-data recursive version,
  6863. // and AnnotationTokensWorker currently transforms the data-recursion
  6864. // algorithm back into a traditional recursion by explicitly calling
  6865. // VisitChildren(). We will need to remove this explicit recursive call.
  6866. W.AnnotateTokens();
  6867. // If we ran into any entities that involve context-sensitive keywords,
  6868. // take another pass through the tokens to mark them as such.
  6869. if (W.hasContextSensitiveKeywords()) {
  6870. for (unsigned I = 0; I != NumTokens; ++I) {
  6871. if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
  6872. continue;
  6873. if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
  6874. IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
  6875. if (const ObjCPropertyDecl *Property =
  6876. dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
  6877. if (Property->getPropertyAttributesAsWritten() != 0 &&
  6878. llvm::StringSwitch<bool>(II->getName())
  6879. .Case("readonly", true)
  6880. .Case("assign", true)
  6881. .Case("unsafe_unretained", true)
  6882. .Case("readwrite", true)
  6883. .Case("retain", true)
  6884. .Case("copy", true)
  6885. .Case("nonatomic", true)
  6886. .Case("atomic", true)
  6887. .Case("getter", true)
  6888. .Case("setter", true)
  6889. .Case("strong", true)
  6890. .Case("weak", true)
  6891. .Case("class", true)
  6892. .Default(false))
  6893. Tokens[I].int_data[0] = CXToken_Keyword;
  6894. }
  6895. continue;
  6896. }
  6897. if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
  6898. Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
  6899. IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
  6900. if (llvm::StringSwitch<bool>(II->getName())
  6901. .Case("in", true)
  6902. .Case("out", true)
  6903. .Case("inout", true)
  6904. .Case("oneway", true)
  6905. .Case("bycopy", true)
  6906. .Case("byref", true)
  6907. .Default(false))
  6908. Tokens[I].int_data[0] = CXToken_Keyword;
  6909. continue;
  6910. }
  6911. if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
  6912. Cursors[I].kind == CXCursor_CXXOverrideAttr) {
  6913. Tokens[I].int_data[0] = CXToken_Keyword;
  6914. continue;
  6915. }
  6916. }
  6917. }
  6918. }
  6919. void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens,
  6920. unsigned NumTokens, CXCursor *Cursors) {
  6921. if (isNotUsableTU(TU)) {
  6922. LOG_BAD_TU(TU);
  6923. return;
  6924. }
  6925. if (NumTokens == 0 || !Tokens || !Cursors) {
  6926. LOG_FUNC_SECTION { *Log << "<null input>"; }
  6927. return;
  6928. }
  6929. LOG_FUNC_SECTION {
  6930. *Log << TU << ' ';
  6931. CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
  6932. CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens - 1]);
  6933. *Log << clang_getRange(bloc, eloc);
  6934. }
  6935. // Any token we don't specifically annotate will have a NULL cursor.
  6936. CXCursor C = clang_getNullCursor();
  6937. for (unsigned I = 0; I != NumTokens; ++I)
  6938. Cursors[I] = C;
  6939. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6940. if (!CXXUnit)
  6941. return;
  6942. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  6943. auto AnnotateTokensImpl = [=]() {
  6944. clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
  6945. };
  6946. llvm::CrashRecoveryContext CRC;
  6947. if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
  6948. fprintf(stderr, "libclang: crash detected while annotating tokens\n");
  6949. }
  6950. }
  6951. //===----------------------------------------------------------------------===//
  6952. // Operations for querying linkage of a cursor.
  6953. //===----------------------------------------------------------------------===//
  6954. CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
  6955. if (!clang_isDeclaration(cursor.kind))
  6956. return CXLinkage_Invalid;
  6957. const Decl *D = cxcursor::getCursorDecl(cursor);
  6958. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
  6959. switch (ND->getLinkageInternal()) {
  6960. case NoLinkage:
  6961. case VisibleNoLinkage:
  6962. return CXLinkage_NoLinkage;
  6963. case ModuleInternalLinkage:
  6964. case InternalLinkage:
  6965. return CXLinkage_Internal;
  6966. case UniqueExternalLinkage:
  6967. return CXLinkage_UniqueExternal;
  6968. case ModuleLinkage:
  6969. case ExternalLinkage:
  6970. return CXLinkage_External;
  6971. };
  6972. return CXLinkage_Invalid;
  6973. }
  6974. //===----------------------------------------------------------------------===//
  6975. // Operations for querying visibility of a cursor.
  6976. //===----------------------------------------------------------------------===//
  6977. CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
  6978. if (!clang_isDeclaration(cursor.kind))
  6979. return CXVisibility_Invalid;
  6980. const Decl *D = cxcursor::getCursorDecl(cursor);
  6981. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
  6982. switch (ND->getVisibility()) {
  6983. case HiddenVisibility:
  6984. return CXVisibility_Hidden;
  6985. case ProtectedVisibility:
  6986. return CXVisibility_Protected;
  6987. case DefaultVisibility:
  6988. return CXVisibility_Default;
  6989. };
  6990. return CXVisibility_Invalid;
  6991. }
  6992. //===----------------------------------------------------------------------===//
  6993. // Operations for querying language of a cursor.
  6994. //===----------------------------------------------------------------------===//
  6995. static CXLanguageKind getDeclLanguage(const Decl *D) {
  6996. if (!D)
  6997. return CXLanguage_C;
  6998. switch (D->getKind()) {
  6999. default:
  7000. break;
  7001. case Decl::ImplicitParam:
  7002. case Decl::ObjCAtDefsField:
  7003. case Decl::ObjCCategory:
  7004. case Decl::ObjCCategoryImpl:
  7005. case Decl::ObjCCompatibleAlias:
  7006. case Decl::ObjCImplementation:
  7007. case Decl::ObjCInterface:
  7008. case Decl::ObjCIvar:
  7009. case Decl::ObjCMethod:
  7010. case Decl::ObjCProperty:
  7011. case Decl::ObjCPropertyImpl:
  7012. case Decl::ObjCProtocol:
  7013. case Decl::ObjCTypeParam:
  7014. return CXLanguage_ObjC;
  7015. case Decl::CXXConstructor:
  7016. case Decl::CXXConversion:
  7017. case Decl::CXXDestructor:
  7018. case Decl::CXXMethod:
  7019. case Decl::CXXRecord:
  7020. case Decl::ClassTemplate:
  7021. case Decl::ClassTemplatePartialSpecialization:
  7022. case Decl::ClassTemplateSpecialization:
  7023. case Decl::Friend:
  7024. case Decl::FriendTemplate:
  7025. case Decl::FunctionTemplate:
  7026. case Decl::LinkageSpec:
  7027. case Decl::Namespace:
  7028. case Decl::NamespaceAlias:
  7029. case Decl::NonTypeTemplateParm:
  7030. case Decl::StaticAssert:
  7031. case Decl::TemplateTemplateParm:
  7032. case Decl::TemplateTypeParm:
  7033. case Decl::UnresolvedUsingTypename:
  7034. case Decl::UnresolvedUsingValue:
  7035. case Decl::Using:
  7036. case Decl::UsingDirective:
  7037. case Decl::UsingShadow:
  7038. return CXLanguage_CPlusPlus;
  7039. }
  7040. return CXLanguage_C;
  7041. }
  7042. static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
  7043. if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
  7044. return CXAvailability_NotAvailable;
  7045. switch (D->getAvailability()) {
  7046. case AR_Available:
  7047. case AR_NotYetIntroduced:
  7048. if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
  7049. return getCursorAvailabilityForDecl(
  7050. cast<Decl>(EnumConst->getDeclContext()));
  7051. return CXAvailability_Available;
  7052. case AR_Deprecated:
  7053. return CXAvailability_Deprecated;
  7054. case AR_Unavailable:
  7055. return CXAvailability_NotAvailable;
  7056. }
  7057. llvm_unreachable("Unknown availability kind!");
  7058. }
  7059. enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
  7060. if (clang_isDeclaration(cursor.kind))
  7061. if (const Decl *D = cxcursor::getCursorDecl(cursor))
  7062. return getCursorAvailabilityForDecl(D);
  7063. return CXAvailability_Available;
  7064. }
  7065. static CXVersion convertVersion(VersionTuple In) {
  7066. CXVersion Out = {-1, -1, -1};
  7067. if (In.empty())
  7068. return Out;
  7069. Out.Major = In.getMajor();
  7070. std::optional<unsigned> Minor = In.getMinor();
  7071. if (Minor)
  7072. Out.Minor = *Minor;
  7073. else
  7074. return Out;
  7075. std::optional<unsigned> Subminor = In.getSubminor();
  7076. if (Subminor)
  7077. Out.Subminor = *Subminor;
  7078. return Out;
  7079. }
  7080. static void getCursorPlatformAvailabilityForDecl(
  7081. const Decl *D, int *always_deprecated, CXString *deprecated_message,
  7082. int *always_unavailable, CXString *unavailable_message,
  7083. SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
  7084. bool HadAvailAttr = false;
  7085. for (auto A : D->attrs()) {
  7086. if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
  7087. HadAvailAttr = true;
  7088. if (always_deprecated)
  7089. *always_deprecated = 1;
  7090. if (deprecated_message) {
  7091. clang_disposeString(*deprecated_message);
  7092. *deprecated_message = cxstring::createDup(Deprecated->getMessage());
  7093. }
  7094. continue;
  7095. }
  7096. if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
  7097. HadAvailAttr = true;
  7098. if (always_unavailable)
  7099. *always_unavailable = 1;
  7100. if (unavailable_message) {
  7101. clang_disposeString(*unavailable_message);
  7102. *unavailable_message = cxstring::createDup(Unavailable->getMessage());
  7103. }
  7104. continue;
  7105. }
  7106. if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
  7107. AvailabilityAttrs.push_back(Avail);
  7108. HadAvailAttr = true;
  7109. }
  7110. }
  7111. if (!HadAvailAttr)
  7112. if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
  7113. return getCursorPlatformAvailabilityForDecl(
  7114. cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
  7115. deprecated_message, always_unavailable, unavailable_message,
  7116. AvailabilityAttrs);
  7117. // If no availability attributes are found, inherit the attribute from the
  7118. // containing decl or the class or category interface decl.
  7119. if (AvailabilityAttrs.empty()) {
  7120. const ObjCContainerDecl *CD = nullptr;
  7121. const DeclContext *DC = D->getDeclContext();
  7122. if (auto *IMD = dyn_cast<ObjCImplementationDecl>(D))
  7123. CD = IMD->getClassInterface();
  7124. else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(D))
  7125. CD = CatD->getClassInterface();
  7126. else if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(D))
  7127. CD = IMD->getCategoryDecl();
  7128. else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(DC))
  7129. CD = ID;
  7130. else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(DC))
  7131. CD = CatD;
  7132. else if (auto *IMD = dyn_cast<ObjCImplementationDecl>(DC))
  7133. CD = IMD->getClassInterface();
  7134. else if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(DC))
  7135. CD = IMD->getCategoryDecl();
  7136. else if (auto *PD = dyn_cast<ObjCProtocolDecl>(DC))
  7137. CD = PD;
  7138. if (CD)
  7139. getCursorPlatformAvailabilityForDecl(
  7140. CD, always_deprecated, deprecated_message, always_unavailable,
  7141. unavailable_message, AvailabilityAttrs);
  7142. return;
  7143. }
  7144. llvm::sort(
  7145. AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
  7146. return LHS->getPlatform()->getName() < RHS->getPlatform()->getName();
  7147. });
  7148. ASTContext &Ctx = D->getASTContext();
  7149. auto It = std::unique(
  7150. AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
  7151. [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
  7152. if (LHS->getPlatform() != RHS->getPlatform())
  7153. return false;
  7154. if (LHS->getIntroduced() == RHS->getIntroduced() &&
  7155. LHS->getDeprecated() == RHS->getDeprecated() &&
  7156. LHS->getObsoleted() == RHS->getObsoleted() &&
  7157. LHS->getMessage() == RHS->getMessage() &&
  7158. LHS->getReplacement() == RHS->getReplacement())
  7159. return true;
  7160. if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
  7161. (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
  7162. (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
  7163. return false;
  7164. if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
  7165. LHS->setIntroduced(Ctx, RHS->getIntroduced());
  7166. if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
  7167. LHS->setDeprecated(Ctx, RHS->getDeprecated());
  7168. if (LHS->getMessage().empty())
  7169. LHS->setMessage(Ctx, RHS->getMessage());
  7170. if (LHS->getReplacement().empty())
  7171. LHS->setReplacement(Ctx, RHS->getReplacement());
  7172. }
  7173. if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
  7174. LHS->setObsoleted(Ctx, RHS->getObsoleted());
  7175. if (LHS->getMessage().empty())
  7176. LHS->setMessage(Ctx, RHS->getMessage());
  7177. if (LHS->getReplacement().empty())
  7178. LHS->setReplacement(Ctx, RHS->getReplacement());
  7179. }
  7180. return true;
  7181. });
  7182. AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
  7183. }
  7184. int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
  7185. CXString *deprecated_message,
  7186. int *always_unavailable,
  7187. CXString *unavailable_message,
  7188. CXPlatformAvailability *availability,
  7189. int availability_size) {
  7190. if (always_deprecated)
  7191. *always_deprecated = 0;
  7192. if (deprecated_message)
  7193. *deprecated_message = cxstring::createEmpty();
  7194. if (always_unavailable)
  7195. *always_unavailable = 0;
  7196. if (unavailable_message)
  7197. *unavailable_message = cxstring::createEmpty();
  7198. if (!clang_isDeclaration(cursor.kind))
  7199. return 0;
  7200. const Decl *D = cxcursor::getCursorDecl(cursor);
  7201. if (!D)
  7202. return 0;
  7203. SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
  7204. getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
  7205. always_unavailable, unavailable_message,
  7206. AvailabilityAttrs);
  7207. for (const auto &Avail : llvm::enumerate(
  7208. llvm::ArrayRef(AvailabilityAttrs).take_front(availability_size))) {
  7209. availability[Avail.index()].Platform =
  7210. cxstring::createDup(Avail.value()->getPlatform()->getName());
  7211. availability[Avail.index()].Introduced =
  7212. convertVersion(Avail.value()->getIntroduced());
  7213. availability[Avail.index()].Deprecated =
  7214. convertVersion(Avail.value()->getDeprecated());
  7215. availability[Avail.index()].Obsoleted =
  7216. convertVersion(Avail.value()->getObsoleted());
  7217. availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
  7218. availability[Avail.index()].Message =
  7219. cxstring::createDup(Avail.value()->getMessage());
  7220. }
  7221. return AvailabilityAttrs.size();
  7222. }
  7223. void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
  7224. clang_disposeString(availability->Platform);
  7225. clang_disposeString(availability->Message);
  7226. }
  7227. CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
  7228. if (clang_isDeclaration(cursor.kind))
  7229. return getDeclLanguage(cxcursor::getCursorDecl(cursor));
  7230. return CXLanguage_Invalid;
  7231. }
  7232. CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
  7233. const Decl *D = cxcursor::getCursorDecl(cursor);
  7234. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  7235. switch (VD->getTLSKind()) {
  7236. case VarDecl::TLS_None:
  7237. return CXTLS_None;
  7238. case VarDecl::TLS_Dynamic:
  7239. return CXTLS_Dynamic;
  7240. case VarDecl::TLS_Static:
  7241. return CXTLS_Static;
  7242. }
  7243. }
  7244. return CXTLS_None;
  7245. }
  7246. /// If the given cursor is the "templated" declaration
  7247. /// describing a class or function template, return the class or
  7248. /// function template.
  7249. static const Decl *maybeGetTemplateCursor(const Decl *D) {
  7250. if (!D)
  7251. return nullptr;
  7252. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  7253. if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
  7254. return FunTmpl;
  7255. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  7256. if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
  7257. return ClassTmpl;
  7258. return D;
  7259. }
  7260. enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
  7261. StorageClass sc = SC_None;
  7262. const Decl *D = getCursorDecl(C);
  7263. if (D) {
  7264. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7265. sc = FD->getStorageClass();
  7266. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  7267. sc = VD->getStorageClass();
  7268. } else {
  7269. return CX_SC_Invalid;
  7270. }
  7271. } else {
  7272. return CX_SC_Invalid;
  7273. }
  7274. switch (sc) {
  7275. case SC_None:
  7276. return CX_SC_None;
  7277. case SC_Extern:
  7278. return CX_SC_Extern;
  7279. case SC_Static:
  7280. return CX_SC_Static;
  7281. case SC_PrivateExtern:
  7282. return CX_SC_PrivateExtern;
  7283. case SC_Auto:
  7284. return CX_SC_Auto;
  7285. case SC_Register:
  7286. return CX_SC_Register;
  7287. }
  7288. llvm_unreachable("Unhandled storage class!");
  7289. }
  7290. CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
  7291. if (clang_isDeclaration(cursor.kind)) {
  7292. if (const Decl *D = getCursorDecl(cursor)) {
  7293. const DeclContext *DC = D->getDeclContext();
  7294. if (!DC)
  7295. return clang_getNullCursor();
  7296. return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
  7297. getCursorTU(cursor));
  7298. }
  7299. }
  7300. if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
  7301. if (const Decl *D = getCursorDecl(cursor))
  7302. return MakeCXCursor(D, getCursorTU(cursor));
  7303. }
  7304. return clang_getNullCursor();
  7305. }
  7306. CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
  7307. if (clang_isDeclaration(cursor.kind)) {
  7308. if (const Decl *D = getCursorDecl(cursor)) {
  7309. const DeclContext *DC = D->getLexicalDeclContext();
  7310. if (!DC)
  7311. return clang_getNullCursor();
  7312. return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
  7313. getCursorTU(cursor));
  7314. }
  7315. }
  7316. // FIXME: Note that we can't easily compute the lexical context of a
  7317. // statement or expression, so we return nothing.
  7318. return clang_getNullCursor();
  7319. }
  7320. CXFile clang_getIncludedFile(CXCursor cursor) {
  7321. if (cursor.kind != CXCursor_InclusionDirective)
  7322. return nullptr;
  7323. const InclusionDirective *ID = getCursorInclusionDirective(cursor);
  7324. OptionalFileEntryRef File = ID->getFile();
  7325. return const_cast<FileEntry *>(File ? &File->getFileEntry() : nullptr);
  7326. }
  7327. unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
  7328. if (C.kind != CXCursor_ObjCPropertyDecl)
  7329. return CXObjCPropertyAttr_noattr;
  7330. unsigned Result = CXObjCPropertyAttr_noattr;
  7331. const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
  7332. ObjCPropertyAttribute::Kind Attr = PD->getPropertyAttributesAsWritten();
  7333. #define SET_CXOBJCPROP_ATTR(A) \
  7334. if (Attr & ObjCPropertyAttribute::kind_##A) \
  7335. Result |= CXObjCPropertyAttr_##A
  7336. SET_CXOBJCPROP_ATTR(readonly);
  7337. SET_CXOBJCPROP_ATTR(getter);
  7338. SET_CXOBJCPROP_ATTR(assign);
  7339. SET_CXOBJCPROP_ATTR(readwrite);
  7340. SET_CXOBJCPROP_ATTR(retain);
  7341. SET_CXOBJCPROP_ATTR(copy);
  7342. SET_CXOBJCPROP_ATTR(nonatomic);
  7343. SET_CXOBJCPROP_ATTR(setter);
  7344. SET_CXOBJCPROP_ATTR(atomic);
  7345. SET_CXOBJCPROP_ATTR(weak);
  7346. SET_CXOBJCPROP_ATTR(strong);
  7347. SET_CXOBJCPROP_ATTR(unsafe_unretained);
  7348. SET_CXOBJCPROP_ATTR(class);
  7349. #undef SET_CXOBJCPROP_ATTR
  7350. return Result;
  7351. }
  7352. CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
  7353. if (C.kind != CXCursor_ObjCPropertyDecl)
  7354. return cxstring::createNull();
  7355. const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
  7356. Selector sel = PD->getGetterName();
  7357. if (sel.isNull())
  7358. return cxstring::createNull();
  7359. return cxstring::createDup(sel.getAsString());
  7360. }
  7361. CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
  7362. if (C.kind != CXCursor_ObjCPropertyDecl)
  7363. return cxstring::createNull();
  7364. const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C));
  7365. Selector sel = PD->getSetterName();
  7366. if (sel.isNull())
  7367. return cxstring::createNull();
  7368. return cxstring::createDup(sel.getAsString());
  7369. }
  7370. unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
  7371. if (!clang_isDeclaration(C.kind))
  7372. return CXObjCDeclQualifier_None;
  7373. Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
  7374. const Decl *D = getCursorDecl(C);
  7375. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  7376. QT = MD->getObjCDeclQualifier();
  7377. else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
  7378. QT = PD->getObjCDeclQualifier();
  7379. if (QT == Decl::OBJC_TQ_None)
  7380. return CXObjCDeclQualifier_None;
  7381. unsigned Result = CXObjCDeclQualifier_None;
  7382. if (QT & Decl::OBJC_TQ_In)
  7383. Result |= CXObjCDeclQualifier_In;
  7384. if (QT & Decl::OBJC_TQ_Inout)
  7385. Result |= CXObjCDeclQualifier_Inout;
  7386. if (QT & Decl::OBJC_TQ_Out)
  7387. Result |= CXObjCDeclQualifier_Out;
  7388. if (QT & Decl::OBJC_TQ_Bycopy)
  7389. Result |= CXObjCDeclQualifier_Bycopy;
  7390. if (QT & Decl::OBJC_TQ_Byref)
  7391. Result |= CXObjCDeclQualifier_Byref;
  7392. if (QT & Decl::OBJC_TQ_Oneway)
  7393. Result |= CXObjCDeclQualifier_Oneway;
  7394. return Result;
  7395. }
  7396. unsigned clang_Cursor_isObjCOptional(CXCursor C) {
  7397. if (!clang_isDeclaration(C.kind))
  7398. return 0;
  7399. const Decl *D = getCursorDecl(C);
  7400. if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
  7401. return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
  7402. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  7403. return MD->getImplementationControl() == ObjCMethodDecl::Optional;
  7404. return 0;
  7405. }
  7406. unsigned clang_Cursor_isVariadic(CXCursor C) {
  7407. if (!clang_isDeclaration(C.kind))
  7408. return 0;
  7409. const Decl *D = getCursorDecl(C);
  7410. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  7411. return FD->isVariadic();
  7412. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  7413. return MD->isVariadic();
  7414. return 0;
  7415. }
  7416. unsigned clang_Cursor_isExternalSymbol(CXCursor C, CXString *language,
  7417. CXString *definedIn,
  7418. unsigned *isGenerated) {
  7419. if (!clang_isDeclaration(C.kind))
  7420. return 0;
  7421. const Decl *D = getCursorDecl(C);
  7422. if (auto *attr = D->getExternalSourceSymbolAttr()) {
  7423. if (language)
  7424. *language = cxstring::createDup(attr->getLanguage());
  7425. if (definedIn)
  7426. *definedIn = cxstring::createDup(attr->getDefinedIn());
  7427. if (isGenerated)
  7428. *isGenerated = attr->getGeneratedDeclaration();
  7429. return 1;
  7430. }
  7431. return 0;
  7432. }
  7433. CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
  7434. if (!clang_isDeclaration(C.kind))
  7435. return clang_getNullRange();
  7436. const Decl *D = getCursorDecl(C);
  7437. ASTContext &Context = getCursorContext(C);
  7438. const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
  7439. if (!RC)
  7440. return clang_getNullRange();
  7441. return cxloc::translateSourceRange(Context, RC->getSourceRange());
  7442. }
  7443. CXString clang_Cursor_getRawCommentText(CXCursor C) {
  7444. if (!clang_isDeclaration(C.kind))
  7445. return cxstring::createNull();
  7446. const Decl *D = getCursorDecl(C);
  7447. ASTContext &Context = getCursorContext(C);
  7448. const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
  7449. StringRef RawText =
  7450. RC ? RC->getRawText(Context.getSourceManager()) : StringRef();
  7451. // Don't duplicate the string because RawText points directly into source
  7452. // code.
  7453. return cxstring::createRef(RawText);
  7454. }
  7455. CXString clang_Cursor_getBriefCommentText(CXCursor C) {
  7456. if (!clang_isDeclaration(C.kind))
  7457. return cxstring::createNull();
  7458. const Decl *D = getCursorDecl(C);
  7459. const ASTContext &Context = getCursorContext(C);
  7460. const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
  7461. if (RC) {
  7462. StringRef BriefText = RC->getBriefText(Context);
  7463. // Don't duplicate the string because RawComment ensures that this memory
  7464. // will not go away.
  7465. return cxstring::createRef(BriefText);
  7466. }
  7467. return cxstring::createNull();
  7468. }
  7469. CXModule clang_Cursor_getModule(CXCursor C) {
  7470. if (C.kind == CXCursor_ModuleImportDecl) {
  7471. if (const ImportDecl *ImportD =
  7472. dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
  7473. return ImportD->getImportedModule();
  7474. }
  7475. return nullptr;
  7476. }
  7477. CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
  7478. if (isNotUsableTU(TU)) {
  7479. LOG_BAD_TU(TU);
  7480. return nullptr;
  7481. }
  7482. if (!File)
  7483. return nullptr;
  7484. FileEntry *FE = static_cast<FileEntry *>(File);
  7485. ASTUnit &Unit = *cxtu::getASTUnit(TU);
  7486. HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
  7487. ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
  7488. return Header.getModule();
  7489. }
  7490. CXFile clang_Module_getASTFile(CXModule CXMod) {
  7491. if (!CXMod)
  7492. return nullptr;
  7493. Module *Mod = static_cast<Module *>(CXMod);
  7494. if (auto File = Mod->getASTFile())
  7495. return const_cast<FileEntry *>(&File->getFileEntry());
  7496. return nullptr;
  7497. }
  7498. CXModule clang_Module_getParent(CXModule CXMod) {
  7499. if (!CXMod)
  7500. return nullptr;
  7501. Module *Mod = static_cast<Module *>(CXMod);
  7502. return Mod->Parent;
  7503. }
  7504. CXString clang_Module_getName(CXModule CXMod) {
  7505. if (!CXMod)
  7506. return cxstring::createEmpty();
  7507. Module *Mod = static_cast<Module *>(CXMod);
  7508. return cxstring::createDup(Mod->Name);
  7509. }
  7510. CXString clang_Module_getFullName(CXModule CXMod) {
  7511. if (!CXMod)
  7512. return cxstring::createEmpty();
  7513. Module *Mod = static_cast<Module *>(CXMod);
  7514. return cxstring::createDup(Mod->getFullModuleName());
  7515. }
  7516. int clang_Module_isSystem(CXModule CXMod) {
  7517. if (!CXMod)
  7518. return 0;
  7519. Module *Mod = static_cast<Module *>(CXMod);
  7520. return Mod->IsSystem;
  7521. }
  7522. unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
  7523. CXModule CXMod) {
  7524. if (isNotUsableTU(TU)) {
  7525. LOG_BAD_TU(TU);
  7526. return 0;
  7527. }
  7528. if (!CXMod)
  7529. return 0;
  7530. Module *Mod = static_cast<Module *>(CXMod);
  7531. FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
  7532. ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
  7533. return TopHeaders.size();
  7534. }
  7535. CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, CXModule CXMod,
  7536. unsigned Index) {
  7537. if (isNotUsableTU(TU)) {
  7538. LOG_BAD_TU(TU);
  7539. return nullptr;
  7540. }
  7541. if (!CXMod)
  7542. return nullptr;
  7543. Module *Mod = static_cast<Module *>(CXMod);
  7544. FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
  7545. ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
  7546. if (Index < TopHeaders.size())
  7547. return const_cast<FileEntry *>(TopHeaders[Index]);
  7548. return nullptr;
  7549. }
  7550. //===----------------------------------------------------------------------===//
  7551. // C++ AST instrospection.
  7552. //===----------------------------------------------------------------------===//
  7553. unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
  7554. if (!clang_isDeclaration(C.kind))
  7555. return 0;
  7556. const Decl *D = cxcursor::getCursorDecl(C);
  7557. const CXXConstructorDecl *Constructor =
  7558. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7559. return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
  7560. }
  7561. unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
  7562. if (!clang_isDeclaration(C.kind))
  7563. return 0;
  7564. const Decl *D = cxcursor::getCursorDecl(C);
  7565. const CXXConstructorDecl *Constructor =
  7566. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7567. return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
  7568. }
  7569. unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
  7570. if (!clang_isDeclaration(C.kind))
  7571. return 0;
  7572. const Decl *D = cxcursor::getCursorDecl(C);
  7573. const CXXConstructorDecl *Constructor =
  7574. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7575. return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
  7576. }
  7577. unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
  7578. if (!clang_isDeclaration(C.kind))
  7579. return 0;
  7580. const Decl *D = cxcursor::getCursorDecl(C);
  7581. const CXXConstructorDecl *Constructor =
  7582. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7583. // Passing 'false' excludes constructors marked 'explicit'.
  7584. return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
  7585. }
  7586. unsigned clang_CXXField_isMutable(CXCursor C) {
  7587. if (!clang_isDeclaration(C.kind))
  7588. return 0;
  7589. if (const auto D = cxcursor::getCursorDecl(C))
  7590. if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
  7591. return FD->isMutable() ? 1 : 0;
  7592. return 0;
  7593. }
  7594. unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
  7595. if (!clang_isDeclaration(C.kind))
  7596. return 0;
  7597. const Decl *D = cxcursor::getCursorDecl(C);
  7598. const CXXMethodDecl *Method =
  7599. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7600. return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
  7601. }
  7602. unsigned clang_CXXMethod_isConst(CXCursor C) {
  7603. if (!clang_isDeclaration(C.kind))
  7604. return 0;
  7605. const Decl *D = cxcursor::getCursorDecl(C);
  7606. const CXXMethodDecl *Method =
  7607. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7608. return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
  7609. }
  7610. unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
  7611. if (!clang_isDeclaration(C.kind))
  7612. return 0;
  7613. const Decl *D = cxcursor::getCursorDecl(C);
  7614. const CXXMethodDecl *Method =
  7615. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7616. return (Method && Method->isDefaulted()) ? 1 : 0;
  7617. }
  7618. unsigned clang_CXXMethod_isDeleted(CXCursor C) {
  7619. if (!clang_isDeclaration(C.kind))
  7620. return 0;
  7621. const Decl *D = cxcursor::getCursorDecl(C);
  7622. const CXXMethodDecl *Method =
  7623. D ? dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7624. return (Method && Method->isDeleted()) ? 1 : 0;
  7625. }
  7626. unsigned clang_CXXMethod_isStatic(CXCursor C) {
  7627. if (!clang_isDeclaration(C.kind))
  7628. return 0;
  7629. const Decl *D = cxcursor::getCursorDecl(C);
  7630. const CXXMethodDecl *Method =
  7631. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7632. return (Method && Method->isStatic()) ? 1 : 0;
  7633. }
  7634. unsigned clang_CXXMethod_isVirtual(CXCursor C) {
  7635. if (!clang_isDeclaration(C.kind))
  7636. return 0;
  7637. const Decl *D = cxcursor::getCursorDecl(C);
  7638. const CXXMethodDecl *Method =
  7639. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7640. return (Method && Method->isVirtual()) ? 1 : 0;
  7641. }
  7642. unsigned clang_CXXMethod_isCopyAssignmentOperator(CXCursor C) {
  7643. if (!clang_isDeclaration(C.kind))
  7644. return 0;
  7645. const Decl *D = cxcursor::getCursorDecl(C);
  7646. const CXXMethodDecl *Method =
  7647. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7648. return (Method && Method->isCopyAssignmentOperator()) ? 1 : 0;
  7649. }
  7650. unsigned clang_CXXMethod_isMoveAssignmentOperator(CXCursor C) {
  7651. if (!clang_isDeclaration(C.kind))
  7652. return 0;
  7653. const Decl *D = cxcursor::getCursorDecl(C);
  7654. const CXXMethodDecl *Method =
  7655. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7656. return (Method && Method->isMoveAssignmentOperator()) ? 1 : 0;
  7657. }
  7658. unsigned clang_CXXRecord_isAbstract(CXCursor C) {
  7659. if (!clang_isDeclaration(C.kind))
  7660. return 0;
  7661. const auto *D = cxcursor::getCursorDecl(C);
  7662. const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
  7663. if (RD)
  7664. RD = RD->getDefinition();
  7665. return (RD && RD->isAbstract()) ? 1 : 0;
  7666. }
  7667. unsigned clang_EnumDecl_isScoped(CXCursor C) {
  7668. if (!clang_isDeclaration(C.kind))
  7669. return 0;
  7670. const Decl *D = cxcursor::getCursorDecl(C);
  7671. auto *Enum = dyn_cast_or_null<EnumDecl>(D);
  7672. return (Enum && Enum->isScoped()) ? 1 : 0;
  7673. }
  7674. //===----------------------------------------------------------------------===//
  7675. // Attribute introspection.
  7676. //===----------------------------------------------------------------------===//
  7677. CXType clang_getIBOutletCollectionType(CXCursor C) {
  7678. if (C.kind != CXCursor_IBOutletCollectionAttr)
  7679. return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
  7680. const IBOutletCollectionAttr *A =
  7681. cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
  7682. return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
  7683. }
  7684. //===----------------------------------------------------------------------===//
  7685. // Inspecting memory usage.
  7686. //===----------------------------------------------------------------------===//
  7687. typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
  7688. static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
  7689. enum CXTUResourceUsageKind k,
  7690. unsigned long amount) {
  7691. CXTUResourceUsageEntry entry = {k, amount};
  7692. entries.push_back(entry);
  7693. }
  7694. const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
  7695. const char *str = "";
  7696. switch (kind) {
  7697. case CXTUResourceUsage_AST:
  7698. str = "ASTContext: expressions, declarations, and types";
  7699. break;
  7700. case CXTUResourceUsage_Identifiers:
  7701. str = "ASTContext: identifiers";
  7702. break;
  7703. case CXTUResourceUsage_Selectors:
  7704. str = "ASTContext: selectors";
  7705. break;
  7706. case CXTUResourceUsage_GlobalCompletionResults:
  7707. str = "Code completion: cached global results";
  7708. break;
  7709. case CXTUResourceUsage_SourceManagerContentCache:
  7710. str = "SourceManager: content cache allocator";
  7711. break;
  7712. case CXTUResourceUsage_AST_SideTables:
  7713. str = "ASTContext: side tables";
  7714. break;
  7715. case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
  7716. str = "SourceManager: malloc'ed memory buffers";
  7717. break;
  7718. case CXTUResourceUsage_SourceManager_Membuffer_MMap:
  7719. str = "SourceManager: mmap'ed memory buffers";
  7720. break;
  7721. case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
  7722. str = "ExternalASTSource: malloc'ed memory buffers";
  7723. break;
  7724. case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
  7725. str = "ExternalASTSource: mmap'ed memory buffers";
  7726. break;
  7727. case CXTUResourceUsage_Preprocessor:
  7728. str = "Preprocessor: malloc'ed memory";
  7729. break;
  7730. case CXTUResourceUsage_PreprocessingRecord:
  7731. str = "Preprocessor: PreprocessingRecord";
  7732. break;
  7733. case CXTUResourceUsage_SourceManager_DataStructures:
  7734. str = "SourceManager: data structures and tables";
  7735. break;
  7736. case CXTUResourceUsage_Preprocessor_HeaderSearch:
  7737. str = "Preprocessor: header search tables";
  7738. break;
  7739. }
  7740. return str;
  7741. }
  7742. CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
  7743. if (isNotUsableTU(TU)) {
  7744. LOG_BAD_TU(TU);
  7745. CXTUResourceUsage usage = {(void *)nullptr, 0, nullptr};
  7746. return usage;
  7747. }
  7748. ASTUnit *astUnit = cxtu::getASTUnit(TU);
  7749. std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
  7750. ASTContext &astContext = astUnit->getASTContext();
  7751. // How much memory is used by AST nodes and types?
  7752. createCXTUResourceUsageEntry(
  7753. *entries, CXTUResourceUsage_AST,
  7754. (unsigned long)astContext.getASTAllocatedMemory());
  7755. // How much memory is used by identifiers?
  7756. createCXTUResourceUsageEntry(
  7757. *entries, CXTUResourceUsage_Identifiers,
  7758. (unsigned long)astContext.Idents.getAllocator().getTotalMemory());
  7759. // How much memory is used for selectors?
  7760. createCXTUResourceUsageEntry(
  7761. *entries, CXTUResourceUsage_Selectors,
  7762. (unsigned long)astContext.Selectors.getTotalMemory());
  7763. // How much memory is used by ASTContext's side tables?
  7764. createCXTUResourceUsageEntry(
  7765. *entries, CXTUResourceUsage_AST_SideTables,
  7766. (unsigned long)astContext.getSideTableAllocatedMemory());
  7767. // How much memory is used for caching global code completion results?
  7768. unsigned long completionBytes = 0;
  7769. if (GlobalCodeCompletionAllocator *completionAllocator =
  7770. astUnit->getCachedCompletionAllocator().get()) {
  7771. completionBytes = completionAllocator->getTotalMemory();
  7772. }
  7773. createCXTUResourceUsageEntry(
  7774. *entries, CXTUResourceUsage_GlobalCompletionResults, completionBytes);
  7775. // How much memory is being used by SourceManager's content cache?
  7776. createCXTUResourceUsageEntry(
  7777. *entries, CXTUResourceUsage_SourceManagerContentCache,
  7778. (unsigned long)astContext.getSourceManager().getContentCacheSize());
  7779. // How much memory is being used by the MemoryBuffer's in SourceManager?
  7780. const SourceManager::MemoryBufferSizes &srcBufs =
  7781. astUnit->getSourceManager().getMemoryBufferSizes();
  7782. createCXTUResourceUsageEntry(*entries,
  7783. CXTUResourceUsage_SourceManager_Membuffer_Malloc,
  7784. (unsigned long)srcBufs.malloc_bytes);
  7785. createCXTUResourceUsageEntry(*entries,
  7786. CXTUResourceUsage_SourceManager_Membuffer_MMap,
  7787. (unsigned long)srcBufs.mmap_bytes);
  7788. createCXTUResourceUsageEntry(
  7789. *entries, CXTUResourceUsage_SourceManager_DataStructures,
  7790. (unsigned long)astContext.getSourceManager().getDataStructureSizes());
  7791. // How much memory is being used by the ExternalASTSource?
  7792. if (ExternalASTSource *esrc = astContext.getExternalSource()) {
  7793. const ExternalASTSource::MemoryBufferSizes &sizes =
  7794. esrc->getMemoryBufferSizes();
  7795. createCXTUResourceUsageEntry(
  7796. *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
  7797. (unsigned long)sizes.malloc_bytes);
  7798. createCXTUResourceUsageEntry(
  7799. *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
  7800. (unsigned long)sizes.mmap_bytes);
  7801. }
  7802. // How much memory is being used by the Preprocessor?
  7803. Preprocessor &pp = astUnit->getPreprocessor();
  7804. createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor,
  7805. pp.getTotalMemory());
  7806. if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
  7807. createCXTUResourceUsageEntry(*entries,
  7808. CXTUResourceUsage_PreprocessingRecord,
  7809. pRec->getTotalMemory());
  7810. }
  7811. createCXTUResourceUsageEntry(*entries,
  7812. CXTUResourceUsage_Preprocessor_HeaderSearch,
  7813. pp.getHeaderSearchInfo().getTotalMemory());
  7814. CXTUResourceUsage usage = {(void *)entries.get(), (unsigned)entries->size(),
  7815. !entries->empty() ? &(*entries)[0] : nullptr};
  7816. (void)entries.release();
  7817. return usage;
  7818. }
  7819. void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
  7820. if (usage.data)
  7821. delete (MemUsageEntries *)usage.data;
  7822. }
  7823. CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
  7824. CXSourceRangeList *skipped = new CXSourceRangeList;
  7825. skipped->count = 0;
  7826. skipped->ranges = nullptr;
  7827. if (isNotUsableTU(TU)) {
  7828. LOG_BAD_TU(TU);
  7829. return skipped;
  7830. }
  7831. if (!file)
  7832. return skipped;
  7833. ASTUnit *astUnit = cxtu::getASTUnit(TU);
  7834. PreprocessingRecord *ppRec =
  7835. astUnit->getPreprocessor().getPreprocessingRecord();
  7836. if (!ppRec)
  7837. return skipped;
  7838. ASTContext &Ctx = astUnit->getASTContext();
  7839. SourceManager &sm = Ctx.getSourceManager();
  7840. FileEntry *fileEntry = static_cast<FileEntry *>(file);
  7841. FileID wantedFileID = sm.translateFile(fileEntry);
  7842. bool isMainFile = wantedFileID == sm.getMainFileID();
  7843. const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
  7844. std::vector<SourceRange> wantedRanges;
  7845. for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(),
  7846. ei = SkippedRanges.end();
  7847. i != ei; ++i) {
  7848. if (sm.getFileID(i->getBegin()) == wantedFileID ||
  7849. sm.getFileID(i->getEnd()) == wantedFileID)
  7850. wantedRanges.push_back(*i);
  7851. else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) ||
  7852. astUnit->isInPreambleFileID(i->getEnd())))
  7853. wantedRanges.push_back(*i);
  7854. }
  7855. skipped->count = wantedRanges.size();
  7856. skipped->ranges = new CXSourceRange[skipped->count];
  7857. for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
  7858. skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
  7859. return skipped;
  7860. }
  7861. CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
  7862. CXSourceRangeList *skipped = new CXSourceRangeList;
  7863. skipped->count = 0;
  7864. skipped->ranges = nullptr;
  7865. if (isNotUsableTU(TU)) {
  7866. LOG_BAD_TU(TU);
  7867. return skipped;
  7868. }
  7869. ASTUnit *astUnit = cxtu::getASTUnit(TU);
  7870. PreprocessingRecord *ppRec =
  7871. astUnit->getPreprocessor().getPreprocessingRecord();
  7872. if (!ppRec)
  7873. return skipped;
  7874. ASTContext &Ctx = astUnit->getASTContext();
  7875. const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
  7876. skipped->count = SkippedRanges.size();
  7877. skipped->ranges = new CXSourceRange[skipped->count];
  7878. for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
  7879. skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
  7880. return skipped;
  7881. }
  7882. void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
  7883. if (ranges) {
  7884. delete[] ranges->ranges;
  7885. delete ranges;
  7886. }
  7887. }
  7888. void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
  7889. CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
  7890. for (unsigned I = 0; I != Usage.numEntries; ++I)
  7891. fprintf(stderr, " %s: %lu\n",
  7892. clang_getTUResourceUsageName(Usage.entries[I].kind),
  7893. Usage.entries[I].amount);
  7894. clang_disposeCXTUResourceUsage(Usage);
  7895. }
  7896. CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor) {
  7897. const Decl *const D = getCursorDecl(cursor);
  7898. if (!D)
  7899. return clang_getNullCursor();
  7900. const auto *const VD = dyn_cast<VarDecl>(D);
  7901. if (!VD)
  7902. return clang_getNullCursor();
  7903. const Expr *const Init = VD->getInit();
  7904. if (!Init)
  7905. return clang_getNullCursor();
  7906. return cxcursor::MakeCXCursor(Init, VD, cxcursor::getCursorTU(cursor));
  7907. }
  7908. int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor) {
  7909. const Decl *const D = getCursorDecl(cursor);
  7910. if (!D)
  7911. return -1;
  7912. const auto *const VD = dyn_cast<VarDecl>(D);
  7913. if (!VD)
  7914. return -1;
  7915. return VD->hasGlobalStorage();
  7916. }
  7917. int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor) {
  7918. const Decl *const D = getCursorDecl(cursor);
  7919. if (!D)
  7920. return -1;
  7921. const auto *const VD = dyn_cast<VarDecl>(D);
  7922. if (!VD)
  7923. return -1;
  7924. return VD->hasExternalStorage();
  7925. }
  7926. //===----------------------------------------------------------------------===//
  7927. // Misc. utility functions.
  7928. //===----------------------------------------------------------------------===//
  7929. /// Default to using our desired 8 MB stack size on "safety" threads.
  7930. static unsigned SafetyStackThreadSize = DesiredStackSize;
  7931. namespace clang {
  7932. bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
  7933. unsigned Size) {
  7934. if (!Size)
  7935. Size = GetSafetyThreadStackSize();
  7936. if (Size && !getenv("LIBCLANG_NOTHREADS"))
  7937. return CRC.RunSafelyOnThread(Fn, Size);
  7938. return CRC.RunSafely(Fn);
  7939. }
  7940. unsigned GetSafetyThreadStackSize() { return SafetyStackThreadSize; }
  7941. void SetSafetyThreadStackSize(unsigned Value) { SafetyStackThreadSize = Value; }
  7942. } // namespace clang
  7943. void clang::setThreadBackgroundPriority() {
  7944. if (getenv("LIBCLANG_BGPRIO_DISABLE"))
  7945. return;
  7946. #if LLVM_ENABLE_THREADS
  7947. // The function name setThreadBackgroundPriority is for historical reasons;
  7948. // Low is more appropriate.
  7949. llvm::set_thread_priority(llvm::ThreadPriority::Low);
  7950. #endif
  7951. }
  7952. void cxindex::printDiagsToStderr(ASTUnit *Unit) {
  7953. if (!Unit)
  7954. return;
  7955. for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
  7956. DEnd = Unit->stored_diag_end();
  7957. D != DEnd; ++D) {
  7958. CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
  7959. CXString Msg =
  7960. clang_formatDiagnostic(&Diag, clang_defaultDiagnosticDisplayOptions());
  7961. fprintf(stderr, "%s\n", clang_getCString(Msg));
  7962. clang_disposeString(Msg);
  7963. }
  7964. #ifdef _WIN32
  7965. // On Windows, force a flush, since there may be multiple copies of
  7966. // stderr and stdout in the file system, all with different buffers
  7967. // but writing to the same device.
  7968. fflush(stderr);
  7969. #endif
  7970. }
  7971. MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
  7972. SourceLocation MacroDefLoc,
  7973. CXTranslationUnit TU) {
  7974. if (MacroDefLoc.isInvalid() || !TU)
  7975. return nullptr;
  7976. if (!II.hadMacroDefinition())
  7977. return nullptr;
  7978. ASTUnit *Unit = cxtu::getASTUnit(TU);
  7979. Preprocessor &PP = Unit->getPreprocessor();
  7980. MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
  7981. if (MD) {
  7982. for (MacroDirective::DefInfo Def = MD->getDefinition(); Def;
  7983. Def = Def.getPreviousDefinition()) {
  7984. if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
  7985. return Def.getMacroInfo();
  7986. }
  7987. }
  7988. return nullptr;
  7989. }
  7990. const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
  7991. CXTranslationUnit TU) {
  7992. if (!MacroDef || !TU)
  7993. return nullptr;
  7994. const IdentifierInfo *II = MacroDef->getName();
  7995. if (!II)
  7996. return nullptr;
  7997. return getMacroInfo(*II, MacroDef->getLocation(), TU);
  7998. }
  7999. MacroDefinitionRecord *
  8000. cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
  8001. CXTranslationUnit TU) {
  8002. if (!MI || !TU)
  8003. return nullptr;
  8004. if (Tok.isNot(tok::raw_identifier))
  8005. return nullptr;
  8006. if (MI->getNumTokens() == 0)
  8007. return nullptr;
  8008. SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
  8009. MI->getDefinitionEndLoc());
  8010. ASTUnit *Unit = cxtu::getASTUnit(TU);
  8011. // Check that the token is inside the definition and not its argument list.
  8012. SourceManager &SM = Unit->getSourceManager();
  8013. if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
  8014. return nullptr;
  8015. if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
  8016. return nullptr;
  8017. Preprocessor &PP = Unit->getPreprocessor();
  8018. PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
  8019. if (!PPRec)
  8020. return nullptr;
  8021. IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
  8022. if (!II.hadMacroDefinition())
  8023. return nullptr;
  8024. // Check that the identifier is not one of the macro arguments.
  8025. if (llvm::is_contained(MI->params(), &II))
  8026. return nullptr;
  8027. MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
  8028. if (!InnerMD)
  8029. return nullptr;
  8030. return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
  8031. }
  8032. MacroDefinitionRecord *
  8033. cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
  8034. CXTranslationUnit TU) {
  8035. if (Loc.isInvalid() || !MI || !TU)
  8036. return nullptr;
  8037. if (MI->getNumTokens() == 0)
  8038. return nullptr;
  8039. ASTUnit *Unit = cxtu::getASTUnit(TU);
  8040. Preprocessor &PP = Unit->getPreprocessor();
  8041. if (!PP.getPreprocessingRecord())
  8042. return nullptr;
  8043. Loc = Unit->getSourceManager().getSpellingLoc(Loc);
  8044. Token Tok;
  8045. if (PP.getRawToken(Loc, Tok))
  8046. return nullptr;
  8047. return checkForMacroInMacroDefinition(MI, Tok, TU);
  8048. }
  8049. CXString clang_getClangVersion() {
  8050. return cxstring::createDup(getClangFullVersion());
  8051. }
  8052. Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
  8053. if (TU) {
  8054. if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
  8055. LogOS << '<' << Unit->getMainFileName() << '>';
  8056. if (Unit->isMainFileAST())
  8057. LogOS << " (" << Unit->getASTFileName() << ')';
  8058. return *this;
  8059. }
  8060. } else {
  8061. LogOS << "<NULL TU>";
  8062. }
  8063. return *this;
  8064. }
  8065. Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
  8066. *this << FE->getName();
  8067. return *this;
  8068. }
  8069. Logger &cxindex::Logger::operator<<(CXCursor cursor) {
  8070. CXString cursorName = clang_getCursorDisplayName(cursor);
  8071. *this << cursorName << "@" << clang_getCursorLocation(cursor);
  8072. clang_disposeString(cursorName);
  8073. return *this;
  8074. }
  8075. Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
  8076. CXFile File;
  8077. unsigned Line, Column;
  8078. clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
  8079. CXString FileName = clang_getFileName(File);
  8080. *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
  8081. clang_disposeString(FileName);
  8082. return *this;
  8083. }
  8084. Logger &cxindex::Logger::operator<<(CXSourceRange range) {
  8085. CXSourceLocation BLoc = clang_getRangeStart(range);
  8086. CXSourceLocation ELoc = clang_getRangeEnd(range);
  8087. CXFile BFile;
  8088. unsigned BLine, BColumn;
  8089. clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
  8090. CXFile EFile;
  8091. unsigned ELine, EColumn;
  8092. clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
  8093. CXString BFileName = clang_getFileName(BFile);
  8094. if (BFile == EFile) {
  8095. *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
  8096. BLine, BColumn, ELine, EColumn);
  8097. } else {
  8098. CXString EFileName = clang_getFileName(EFile);
  8099. *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), BLine,
  8100. BColumn)
  8101. << llvm::format("%s:%d:%d]", clang_getCString(EFileName), ELine,
  8102. EColumn);
  8103. clang_disposeString(EFileName);
  8104. }
  8105. clang_disposeString(BFileName);
  8106. return *this;
  8107. }
  8108. Logger &cxindex::Logger::operator<<(CXString Str) {
  8109. *this << clang_getCString(Str);
  8110. return *this;
  8111. }
  8112. Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
  8113. LogOS << Fmt;
  8114. return *this;
  8115. }
  8116. static llvm::ManagedStatic<std::mutex> LoggingMutex;
  8117. cxindex::Logger::~Logger() {
  8118. std::lock_guard<std::mutex> L(*LoggingMutex);
  8119. static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
  8120. raw_ostream &OS = llvm::errs();
  8121. OS << "[libclang:" << Name << ':';
  8122. #ifdef USE_DARWIN_THREADS
  8123. // TODO: Portability.
  8124. mach_port_t tid = pthread_mach_thread_np(pthread_self());
  8125. OS << tid << ':';
  8126. #endif
  8127. llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
  8128. OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
  8129. OS << Msg << '\n';
  8130. if (Trace) {
  8131. llvm::sys::PrintStackTrace(OS);
  8132. OS << "--------------------------------------------------\n";
  8133. }
  8134. }