ASTUnit.cpp 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731
  1. //===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // ASTUnit Implementation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/DeclVisitor.h"
  17. #include "clang/AST/TypeOrdering.h"
  18. #include "clang/AST/StmtVisitor.h"
  19. #include "clang/Driver/Compilation.h"
  20. #include "clang/Driver/Driver.h"
  21. #include "clang/Driver/Job.h"
  22. #include "clang/Driver/ArgList.h"
  23. #include "clang/Driver/Options.h"
  24. #include "clang/Driver/Tool.h"
  25. #include "clang/Frontend/CompilerInstance.h"
  26. #include "clang/Frontend/FrontendActions.h"
  27. #include "clang/Frontend/FrontendDiagnostic.h"
  28. #include "clang/Frontend/FrontendOptions.h"
  29. #include "clang/Frontend/MultiplexConsumer.h"
  30. #include "clang/Frontend/Utils.h"
  31. #include "clang/Serialization/ASTReader.h"
  32. #include "clang/Serialization/ASTWriter.h"
  33. #include "clang/Lex/HeaderSearch.h"
  34. #include "clang/Lex/Preprocessor.h"
  35. #include "clang/Basic/TargetOptions.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Basic/Diagnostic.h"
  38. #include "llvm/ADT/ArrayRef.h"
  39. #include "llvm/ADT/StringExtras.h"
  40. #include "llvm/ADT/StringSet.h"
  41. #include "llvm/Support/Atomic.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/Host.h"
  44. #include "llvm/Support/Path.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "llvm/Support/Timer.h"
  47. #include "llvm/Support/FileSystem.h"
  48. #include "llvm/Support/Mutex.h"
  49. #include "llvm/Support/MutexGuard.h"
  50. #include "llvm/Support/CrashRecoveryContext.h"
  51. #include <cstdlib>
  52. #include <cstdio>
  53. #include <sys/stat.h>
  54. using namespace clang;
  55. using llvm::TimeRecord;
  56. namespace {
  57. class SimpleTimer {
  58. bool WantTiming;
  59. TimeRecord Start;
  60. std::string Output;
  61. public:
  62. explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
  63. if (WantTiming)
  64. Start = TimeRecord::getCurrentTime();
  65. }
  66. void setOutput(const Twine &Output) {
  67. if (WantTiming)
  68. this->Output = Output.str();
  69. }
  70. ~SimpleTimer() {
  71. if (WantTiming) {
  72. TimeRecord Elapsed = TimeRecord::getCurrentTime();
  73. Elapsed -= Start;
  74. llvm::errs() << Output << ':';
  75. Elapsed.print(Elapsed, llvm::errs());
  76. llvm::errs() << '\n';
  77. }
  78. }
  79. };
  80. struct OnDiskData {
  81. /// \brief The file in which the precompiled preamble is stored.
  82. std::string PreambleFile;
  83. /// \brief Temporary files that should be removed when the ASTUnit is
  84. /// destroyed.
  85. SmallVector<llvm::sys::Path, 4> TemporaryFiles;
  86. /// \brief Erase temporary files.
  87. void CleanTemporaryFiles();
  88. /// \brief Erase the preamble file.
  89. void CleanPreambleFile();
  90. /// \brief Erase temporary files and the preamble file.
  91. void Cleanup();
  92. };
  93. }
  94. static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
  95. static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
  96. return M;
  97. }
  98. static void cleanupOnDiskMapAtExit(void);
  99. typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
  100. static OnDiskDataMap &getOnDiskDataMap() {
  101. static OnDiskDataMap M;
  102. static bool hasRegisteredAtExit = false;
  103. if (!hasRegisteredAtExit) {
  104. hasRegisteredAtExit = true;
  105. atexit(cleanupOnDiskMapAtExit);
  106. }
  107. return M;
  108. }
  109. static void cleanupOnDiskMapAtExit(void) {
  110. // No mutex required here since we are leaving the program.
  111. OnDiskDataMap &M = getOnDiskDataMap();
  112. for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
  113. // We don't worry about freeing the memory associated with OnDiskDataMap.
  114. // All we care about is erasing stale files.
  115. I->second->Cleanup();
  116. }
  117. }
  118. static OnDiskData &getOnDiskData(const ASTUnit *AU) {
  119. // We require the mutex since we are modifying the structure of the
  120. // DenseMap.
  121. llvm::MutexGuard Guard(getOnDiskMutex());
  122. OnDiskDataMap &M = getOnDiskDataMap();
  123. OnDiskData *&D = M[AU];
  124. if (!D)
  125. D = new OnDiskData();
  126. return *D;
  127. }
  128. static void erasePreambleFile(const ASTUnit *AU) {
  129. getOnDiskData(AU).CleanPreambleFile();
  130. }
  131. static void removeOnDiskEntry(const ASTUnit *AU) {
  132. // We require the mutex since we are modifying the structure of the
  133. // DenseMap.
  134. llvm::MutexGuard Guard(getOnDiskMutex());
  135. OnDiskDataMap &M = getOnDiskDataMap();
  136. OnDiskDataMap::iterator I = M.find(AU);
  137. if (I != M.end()) {
  138. I->second->Cleanup();
  139. delete I->second;
  140. M.erase(AU);
  141. }
  142. }
  143. static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
  144. getOnDiskData(AU).PreambleFile = preambleFile;
  145. }
  146. static const std::string &getPreambleFile(const ASTUnit *AU) {
  147. return getOnDiskData(AU).PreambleFile;
  148. }
  149. void OnDiskData::CleanTemporaryFiles() {
  150. for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
  151. TemporaryFiles[I].eraseFromDisk();
  152. TemporaryFiles.clear();
  153. }
  154. void OnDiskData::CleanPreambleFile() {
  155. if (!PreambleFile.empty()) {
  156. llvm::sys::Path(PreambleFile).eraseFromDisk();
  157. PreambleFile.clear();
  158. }
  159. }
  160. void OnDiskData::Cleanup() {
  161. CleanTemporaryFiles();
  162. CleanPreambleFile();
  163. }
  164. void ASTUnit::clearFileLevelDecls() {
  165. for (FileDeclsTy::iterator
  166. I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
  167. delete I->second;
  168. FileDecls.clear();
  169. }
  170. void ASTUnit::CleanTemporaryFiles() {
  171. getOnDiskData(this).CleanTemporaryFiles();
  172. }
  173. void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
  174. getOnDiskData(this).TemporaryFiles.push_back(TempFile);
  175. }
  176. /// \brief After failing to build a precompiled preamble (due to
  177. /// errors in the source that occurs in the preamble), the number of
  178. /// reparses during which we'll skip even trying to precompile the
  179. /// preamble.
  180. const unsigned DefaultPreambleRebuildInterval = 5;
  181. /// \brief Tracks the number of ASTUnit objects that are currently active.
  182. ///
  183. /// Used for debugging purposes only.
  184. static llvm::sys::cas_flag ActiveASTUnitObjects;
  185. ASTUnit::ASTUnit(bool _MainFileIsAST)
  186. : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
  187. MainFileIsAST(_MainFileIsAST),
  188. TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
  189. OwnsRemappedFileBuffers(true),
  190. NumStoredDiagnosticsFromDriver(0),
  191. PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
  192. NumWarningsInPreamble(0),
  193. ShouldCacheCodeCompletionResults(false),
  194. NestedMacroExpansions(true),
  195. CompletionCacheTopLevelHashValue(0),
  196. PreambleTopLevelHashValue(0),
  197. CurrentTopLevelHashValue(0),
  198. UnsafeToFree(false) {
  199. if (getenv("LIBCLANG_OBJTRACKING")) {
  200. llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
  201. fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
  202. }
  203. }
  204. ASTUnit::~ASTUnit() {
  205. clearFileLevelDecls();
  206. // Clean up the temporary files and the preamble file.
  207. removeOnDiskEntry(this);
  208. // Free the buffers associated with remapped files. We are required to
  209. // perform this operation here because we explicitly request that the
  210. // compiler instance *not* free these buffers for each invocation of the
  211. // parser.
  212. if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
  213. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  214. for (PreprocessorOptions::remapped_file_buffer_iterator
  215. FB = PPOpts.remapped_file_buffer_begin(),
  216. FBEnd = PPOpts.remapped_file_buffer_end();
  217. FB != FBEnd;
  218. ++FB)
  219. delete FB->second;
  220. }
  221. delete SavedMainFileBuffer;
  222. delete PreambleBuffer;
  223. ClearCachedCompletionResults();
  224. if (getenv("LIBCLANG_OBJTRACKING")) {
  225. llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
  226. fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
  227. }
  228. }
  229. /// \brief Determine the set of code-completion contexts in which this
  230. /// declaration should be shown.
  231. static unsigned getDeclShowContexts(NamedDecl *ND,
  232. const LangOptions &LangOpts,
  233. bool &IsNestedNameSpecifier) {
  234. IsNestedNameSpecifier = false;
  235. if (isa<UsingShadowDecl>(ND))
  236. ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
  237. if (!ND)
  238. return 0;
  239. unsigned Contexts = 0;
  240. if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
  241. isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
  242. // Types can appear in these contexts.
  243. if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
  244. Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
  245. | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  246. | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
  247. | (1 << (CodeCompletionContext::CCC_Statement - 1))
  248. | (1 << (CodeCompletionContext::CCC_Type - 1))
  249. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
  250. // In C++, types can appear in expressions contexts (for functional casts).
  251. if (LangOpts.CPlusPlus)
  252. Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
  253. // In Objective-C, message sends can send interfaces. In Objective-C++,
  254. // all types are available due to functional casts.
  255. if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
  256. Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
  257. // In Objective-C, you can only be a subclass of another Objective-C class
  258. if (isa<ObjCInterfaceDecl>(ND))
  259. Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
  260. // Deal with tag names.
  261. if (isa<EnumDecl>(ND)) {
  262. Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
  263. // Part of the nested-name-specifier in C++0x.
  264. if (LangOpts.CPlusPlus0x)
  265. IsNestedNameSpecifier = true;
  266. } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
  267. if (Record->isUnion())
  268. Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
  269. else
  270. Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
  271. if (LangOpts.CPlusPlus)
  272. IsNestedNameSpecifier = true;
  273. } else if (isa<ClassTemplateDecl>(ND))
  274. IsNestedNameSpecifier = true;
  275. } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  276. // Values can appear in these contexts.
  277. Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
  278. | (1 << (CodeCompletionContext::CCC_Expression - 1))
  279. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
  280. | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
  281. } else if (isa<ObjCProtocolDecl>(ND)) {
  282. Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
  283. } else if (isa<ObjCCategoryDecl>(ND)) {
  284. Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
  285. } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
  286. Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
  287. // Part of the nested-name-specifier.
  288. IsNestedNameSpecifier = true;
  289. }
  290. return Contexts;
  291. }
  292. void ASTUnit::CacheCodeCompletionResults() {
  293. if (!TheSema)
  294. return;
  295. SimpleTimer Timer(WantTiming);
  296. Timer.setOutput("Cache global code completions for " + getMainFileName());
  297. // Clear out the previous results.
  298. ClearCachedCompletionResults();
  299. // Gather the set of global code completions.
  300. typedef CodeCompletionResult Result;
  301. SmallVector<Result, 8> Results;
  302. CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
  303. TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
  304. // Translate global code completions into cached completions.
  305. llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
  306. for (unsigned I = 0, N = Results.size(); I != N; ++I) {
  307. switch (Results[I].Kind) {
  308. case Result::RK_Declaration: {
  309. bool IsNestedNameSpecifier = false;
  310. CachedCodeCompletionResult CachedResult;
  311. CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
  312. *CachedCompletionAllocator);
  313. CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
  314. Ctx->getLangOptions(),
  315. IsNestedNameSpecifier);
  316. CachedResult.Priority = Results[I].Priority;
  317. CachedResult.Kind = Results[I].CursorKind;
  318. CachedResult.Availability = Results[I].Availability;
  319. // Keep track of the type of this completion in an ASTContext-agnostic
  320. // way.
  321. QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
  322. if (UsageType.isNull()) {
  323. CachedResult.TypeClass = STC_Void;
  324. CachedResult.Type = 0;
  325. } else {
  326. CanQualType CanUsageType
  327. = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
  328. CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
  329. // Determine whether we have already seen this type. If so, we save
  330. // ourselves the work of formatting the type string by using the
  331. // temporary, CanQualType-based hash table to find the associated value.
  332. unsigned &TypeValue = CompletionTypes[CanUsageType];
  333. if (TypeValue == 0) {
  334. TypeValue = CompletionTypes.size();
  335. CachedCompletionTypes[QualType(CanUsageType).getAsString()]
  336. = TypeValue;
  337. }
  338. CachedResult.Type = TypeValue;
  339. }
  340. CachedCompletionResults.push_back(CachedResult);
  341. /// Handle nested-name-specifiers in C++.
  342. if (TheSema->Context.getLangOptions().CPlusPlus &&
  343. IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
  344. // The contexts in which a nested-name-specifier can appear in C++.
  345. unsigned NNSContexts
  346. = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
  347. | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  348. | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
  349. | (1 << (CodeCompletionContext::CCC_Statement - 1))
  350. | (1 << (CodeCompletionContext::CCC_Expression - 1))
  351. | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
  352. | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
  353. | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
  354. | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
  355. | (1 << (CodeCompletionContext::CCC_Type - 1))
  356. | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
  357. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
  358. if (isa<NamespaceDecl>(Results[I].Declaration) ||
  359. isa<NamespaceAliasDecl>(Results[I].Declaration))
  360. NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
  361. if (unsigned RemainingContexts
  362. = NNSContexts & ~CachedResult.ShowInContexts) {
  363. // If there any contexts where this completion can be a
  364. // nested-name-specifier but isn't already an option, create a
  365. // nested-name-specifier completion.
  366. Results[I].StartsNestedNameSpecifier = true;
  367. CachedResult.Completion
  368. = Results[I].CreateCodeCompletionString(*TheSema,
  369. *CachedCompletionAllocator);
  370. CachedResult.ShowInContexts = RemainingContexts;
  371. CachedResult.Priority = CCP_NestedNameSpecifier;
  372. CachedResult.TypeClass = STC_Void;
  373. CachedResult.Type = 0;
  374. CachedCompletionResults.push_back(CachedResult);
  375. }
  376. }
  377. break;
  378. }
  379. case Result::RK_Keyword:
  380. case Result::RK_Pattern:
  381. // Ignore keywords and patterns; we don't care, since they are so
  382. // easily regenerated.
  383. break;
  384. case Result::RK_Macro: {
  385. CachedCodeCompletionResult CachedResult;
  386. CachedResult.Completion
  387. = Results[I].CreateCodeCompletionString(*TheSema,
  388. *CachedCompletionAllocator);
  389. CachedResult.ShowInContexts
  390. = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
  391. | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
  392. | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
  393. | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  394. | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
  395. | (1 << (CodeCompletionContext::CCC_Statement - 1))
  396. | (1 << (CodeCompletionContext::CCC_Expression - 1))
  397. | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
  398. | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
  399. | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
  400. | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
  401. | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
  402. CachedResult.Priority = Results[I].Priority;
  403. CachedResult.Kind = Results[I].CursorKind;
  404. CachedResult.Availability = Results[I].Availability;
  405. CachedResult.TypeClass = STC_Void;
  406. CachedResult.Type = 0;
  407. CachedCompletionResults.push_back(CachedResult);
  408. break;
  409. }
  410. }
  411. }
  412. // Save the current top-level hash value.
  413. CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
  414. }
  415. void ASTUnit::ClearCachedCompletionResults() {
  416. CachedCompletionResults.clear();
  417. CachedCompletionTypes.clear();
  418. CachedCompletionAllocator = 0;
  419. }
  420. namespace {
  421. /// \brief Gathers information from ASTReader that will be used to initialize
  422. /// a Preprocessor.
  423. class ASTInfoCollector : public ASTReaderListener {
  424. Preprocessor &PP;
  425. ASTContext &Context;
  426. LangOptions &LangOpt;
  427. HeaderSearch &HSI;
  428. llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
  429. std::string &Predefines;
  430. unsigned &Counter;
  431. unsigned NumHeaderInfos;
  432. bool InitializedLanguage;
  433. public:
  434. ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
  435. HeaderSearch &HSI,
  436. llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
  437. std::string &Predefines,
  438. unsigned &Counter)
  439. : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
  440. Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
  441. InitializedLanguage(false) {}
  442. virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
  443. if (InitializedLanguage)
  444. return false;
  445. LangOpt = LangOpts;
  446. // Initialize the preprocessor.
  447. PP.Initialize(*Target);
  448. // Initialize the ASTContext
  449. Context.InitBuiltinTypes(*Target);
  450. InitializedLanguage = true;
  451. return false;
  452. }
  453. virtual bool ReadTargetTriple(StringRef Triple) {
  454. // If we've already initialized the target, don't do it again.
  455. if (Target)
  456. return false;
  457. // FIXME: This is broken, we should store the TargetOptions in the AST file.
  458. TargetOptions TargetOpts;
  459. TargetOpts.ABI = "";
  460. TargetOpts.CXXABI = "";
  461. TargetOpts.CPU = "";
  462. TargetOpts.Features.clear();
  463. TargetOpts.Triple = Triple;
  464. Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
  465. return false;
  466. }
  467. virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
  468. StringRef OriginalFileName,
  469. std::string &SuggestedPredefines,
  470. FileManager &FileMgr) {
  471. Predefines = Buffers[0].Data;
  472. for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
  473. Predefines += Buffers[I].Data;
  474. }
  475. return false;
  476. }
  477. virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
  478. HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
  479. }
  480. virtual void ReadCounter(unsigned Value) {
  481. Counter = Value;
  482. }
  483. };
  484. class StoredDiagnosticConsumer : public DiagnosticConsumer {
  485. SmallVectorImpl<StoredDiagnostic> &StoredDiags;
  486. public:
  487. explicit StoredDiagnosticConsumer(
  488. SmallVectorImpl<StoredDiagnostic> &StoredDiags)
  489. : StoredDiags(StoredDiags) { }
  490. virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
  491. const Diagnostic &Info);
  492. DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
  493. // Just drop any diagnostics that come from cloned consumers; they'll
  494. // have different source managers anyway.
  495. return new IgnoringDiagConsumer();
  496. }
  497. };
  498. /// \brief RAII object that optionally captures diagnostics, if
  499. /// there is no diagnostic client to capture them already.
  500. class CaptureDroppedDiagnostics {
  501. DiagnosticsEngine &Diags;
  502. StoredDiagnosticConsumer Client;
  503. DiagnosticConsumer *PreviousClient;
  504. public:
  505. CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
  506. SmallVectorImpl<StoredDiagnostic> &StoredDiags)
  507. : Diags(Diags), Client(StoredDiags), PreviousClient(0)
  508. {
  509. if (RequestCapture || Diags.getClient() == 0) {
  510. PreviousClient = Diags.takeClient();
  511. Diags.setClient(&Client);
  512. }
  513. }
  514. ~CaptureDroppedDiagnostics() {
  515. if (Diags.getClient() == &Client) {
  516. Diags.takeClient();
  517. Diags.setClient(PreviousClient);
  518. }
  519. }
  520. };
  521. } // anonymous namespace
  522. void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
  523. const Diagnostic &Info) {
  524. // Default implementation (Warnings/errors count).
  525. DiagnosticConsumer::HandleDiagnostic(Level, Info);
  526. StoredDiags.push_back(StoredDiagnostic(Level, Info));
  527. }
  528. const std::string &ASTUnit::getOriginalSourceFileName() {
  529. return OriginalSourceFile;
  530. }
  531. llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
  532. std::string *ErrorStr) {
  533. assert(FileMgr);
  534. return FileMgr->getBufferForFile(Filename, ErrorStr);
  535. }
  536. /// \brief Configure the diagnostics object for use with ASTUnit.
  537. void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
  538. const char **ArgBegin, const char **ArgEnd,
  539. ASTUnit &AST, bool CaptureDiagnostics) {
  540. if (!Diags.getPtr()) {
  541. // No diagnostics engine was provided, so create our own diagnostics object
  542. // with the default options.
  543. DiagnosticOptions DiagOpts;
  544. DiagnosticConsumer *Client = 0;
  545. if (CaptureDiagnostics)
  546. Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
  547. Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
  548. ArgBegin, Client);
  549. } else if (CaptureDiagnostics) {
  550. Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
  551. }
  552. }
  553. ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
  554. llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  555. const FileSystemOptions &FileSystemOpts,
  556. bool OnlyLocalDecls,
  557. RemappedFile *RemappedFiles,
  558. unsigned NumRemappedFiles,
  559. bool CaptureDiagnostics) {
  560. llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
  561. // Recover resources if we crash before exiting this method.
  562. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  563. ASTUnitCleanup(AST.get());
  564. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  565. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
  566. DiagCleanup(Diags.getPtr());
  567. ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
  568. AST->OnlyLocalDecls = OnlyLocalDecls;
  569. AST->CaptureDiagnostics = CaptureDiagnostics;
  570. AST->Diagnostics = Diags;
  571. AST->FileMgr = new FileManager(FileSystemOpts);
  572. AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
  573. AST->getFileManager());
  574. AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
  575. AST->getDiagnostics()));
  576. for (unsigned I = 0; I != NumRemappedFiles; ++I) {
  577. FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
  578. if (const llvm::MemoryBuffer *
  579. memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
  580. // Create the file entry for the file that we're mapping from.
  581. const FileEntry *FromFile
  582. = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
  583. memBuf->getBufferSize(),
  584. 0);
  585. if (!FromFile) {
  586. AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
  587. << RemappedFiles[I].first;
  588. delete memBuf;
  589. continue;
  590. }
  591. // Override the contents of the "from" file with the contents of
  592. // the "to" file.
  593. AST->getSourceManager().overrideFileContents(FromFile, memBuf);
  594. } else {
  595. const char *fname = fileOrBuf.get<const char *>();
  596. const FileEntry *ToFile = AST->FileMgr->getFile(fname);
  597. if (!ToFile) {
  598. AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
  599. << RemappedFiles[I].first << fname;
  600. continue;
  601. }
  602. // Create the file entry for the file that we're mapping from.
  603. const FileEntry *FromFile
  604. = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
  605. ToFile->getSize(),
  606. 0);
  607. if (!FromFile) {
  608. AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
  609. << RemappedFiles[I].first;
  610. delete memBuf;
  611. continue;
  612. }
  613. // Override the contents of the "from" file with the contents of
  614. // the "to" file.
  615. AST->getSourceManager().overrideFileContents(FromFile, ToFile);
  616. }
  617. }
  618. // Gather Info for preprocessor construction later on.
  619. HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
  620. std::string Predefines;
  621. unsigned Counter;
  622. llvm::OwningPtr<ASTReader> Reader;
  623. AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
  624. /*Target=*/0, AST->getSourceManager(), HeaderInfo,
  625. *AST,
  626. /*IILookup=*/0,
  627. /*OwnsHeaderSearch=*/false,
  628. /*DelayInitialization=*/true);
  629. Preprocessor &PP = *AST->PP;
  630. AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
  631. AST->getSourceManager(),
  632. /*Target=*/0,
  633. PP.getIdentifierTable(),
  634. PP.getSelectorTable(),
  635. PP.getBuiltinInfo(),
  636. /* size_reserve = */0,
  637. /*DelayInitialization=*/true);
  638. ASTContext &Context = *AST->Ctx;
  639. Reader.reset(new ASTReader(PP, Context));
  640. // Recover resources if we crash before exiting this method.
  641. llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
  642. ReaderCleanup(Reader.get());
  643. Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
  644. AST->ASTFileLangOpts, HeaderInfo,
  645. AST->Target, Predefines, Counter));
  646. switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
  647. case ASTReader::Success:
  648. break;
  649. case ASTReader::Failure:
  650. case ASTReader::IgnorePCH:
  651. AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
  652. return NULL;
  653. }
  654. AST->OriginalSourceFile = Reader->getOriginalSourceFile();
  655. PP.setPredefines(Reader->getSuggestedPredefines());
  656. PP.setCounterValue(Counter);
  657. // Attach the AST reader to the AST context as an external AST
  658. // source, so that declarations will be deserialized from the
  659. // AST file as needed.
  660. ASTReader *ReaderPtr = Reader.get();
  661. llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
  662. // Unregister the cleanup for ASTReader. It will get cleaned up
  663. // by the ASTUnit cleanup.
  664. ReaderCleanup.unregister();
  665. Context.setExternalSource(Source);
  666. // Create an AST consumer, even though it isn't used.
  667. AST->Consumer.reset(new ASTConsumer);
  668. // Create a semantic analysis object and tell the AST reader about it.
  669. AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
  670. AST->TheSema->Initialize();
  671. ReaderPtr->InitializeSema(*AST->TheSema);
  672. AST->Reader = ReaderPtr;
  673. return AST.take();
  674. }
  675. namespace {
  676. /// \brief Preprocessor callback class that updates a hash value with the names
  677. /// of all macros that have been defined by the translation unit.
  678. class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
  679. unsigned &Hash;
  680. public:
  681. explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
  682. virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
  683. Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
  684. }
  685. };
  686. /// \brief Add the given declaration to the hash of all top-level entities.
  687. void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
  688. if (!D)
  689. return;
  690. DeclContext *DC = D->getDeclContext();
  691. if (!DC)
  692. return;
  693. if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
  694. return;
  695. if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
  696. if (ND->getIdentifier())
  697. Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
  698. else if (DeclarationName Name = ND->getDeclName()) {
  699. std::string NameStr = Name.getAsString();
  700. Hash = llvm::HashString(NameStr, Hash);
  701. }
  702. return;
  703. }
  704. if (ObjCForwardProtocolDecl *Forward
  705. = dyn_cast<ObjCForwardProtocolDecl>(D)) {
  706. for (ObjCForwardProtocolDecl::protocol_iterator
  707. P = Forward->protocol_begin(),
  708. PEnd = Forward->protocol_end();
  709. P != PEnd; ++P)
  710. AddTopLevelDeclarationToHash(*P, Hash);
  711. return;
  712. }
  713. if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
  714. AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
  715. return;
  716. }
  717. }
  718. class TopLevelDeclTrackerConsumer : public ASTConsumer {
  719. ASTUnit &Unit;
  720. unsigned &Hash;
  721. public:
  722. TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
  723. : Unit(_Unit), Hash(Hash) {
  724. Hash = 0;
  725. }
  726. void handleTopLevelDecl(Decl *D) {
  727. if (!D)
  728. return;
  729. // FIXME: Currently ObjC method declarations are incorrectly being
  730. // reported as top-level declarations, even though their DeclContext
  731. // is the containing ObjC @interface/@implementation. This is a
  732. // fundamental problem in the parser right now.
  733. if (isa<ObjCMethodDecl>(D))
  734. return;
  735. AddTopLevelDeclarationToHash(D, Hash);
  736. Unit.addTopLevelDecl(D);
  737. handleFileLevelDecl(D);
  738. }
  739. void handleFileLevelDecl(Decl *D) {
  740. Unit.addFileLevelDecl(D);
  741. if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
  742. for (NamespaceDecl::decl_iterator
  743. I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
  744. handleFileLevelDecl(*I);
  745. }
  746. }
  747. bool HandleTopLevelDecl(DeclGroupRef D) {
  748. for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
  749. handleTopLevelDecl(*it);
  750. return true;
  751. }
  752. // We're not interested in "interesting" decls.
  753. void HandleInterestingDecl(DeclGroupRef) {}
  754. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
  755. for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
  756. handleTopLevelDecl(*it);
  757. }
  758. };
  759. class TopLevelDeclTrackerAction : public ASTFrontendAction {
  760. public:
  761. ASTUnit &Unit;
  762. virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
  763. StringRef InFile) {
  764. CI.getPreprocessor().addPPCallbacks(
  765. new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
  766. return new TopLevelDeclTrackerConsumer(Unit,
  767. Unit.getCurrentTopLevelHashValue());
  768. }
  769. public:
  770. TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
  771. virtual bool hasCodeCompletionSupport() const { return false; }
  772. virtual TranslationUnitKind getTranslationUnitKind() {
  773. return Unit.getTranslationUnitKind();
  774. }
  775. };
  776. class PrecompilePreambleConsumer : public PCHGenerator {
  777. ASTUnit &Unit;
  778. unsigned &Hash;
  779. std::vector<Decl *> TopLevelDecls;
  780. public:
  781. PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
  782. StringRef isysroot, raw_ostream *Out)
  783. : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
  784. Hash(Unit.getCurrentTopLevelHashValue()) {
  785. Hash = 0;
  786. }
  787. virtual bool HandleTopLevelDecl(DeclGroupRef D) {
  788. for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
  789. Decl *D = *it;
  790. // FIXME: Currently ObjC method declarations are incorrectly being
  791. // reported as top-level declarations, even though their DeclContext
  792. // is the containing ObjC @interface/@implementation. This is a
  793. // fundamental problem in the parser right now.
  794. if (isa<ObjCMethodDecl>(D))
  795. continue;
  796. AddTopLevelDeclarationToHash(D, Hash);
  797. TopLevelDecls.push_back(D);
  798. }
  799. return true;
  800. }
  801. virtual void HandleTranslationUnit(ASTContext &Ctx) {
  802. PCHGenerator::HandleTranslationUnit(Ctx);
  803. if (!Unit.getDiagnostics().hasErrorOccurred()) {
  804. // Translate the top-level declarations we captured during
  805. // parsing into declaration IDs in the precompiled
  806. // preamble. This will allow us to deserialize those top-level
  807. // declarations when requested.
  808. for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
  809. Unit.addTopLevelDeclFromPreamble(
  810. getWriter().getDeclID(TopLevelDecls[I]));
  811. }
  812. }
  813. };
  814. class PrecompilePreambleAction : public ASTFrontendAction {
  815. ASTUnit &Unit;
  816. public:
  817. explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
  818. virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
  819. StringRef InFile) {
  820. std::string Sysroot;
  821. std::string OutputFile;
  822. raw_ostream *OS = 0;
  823. if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
  824. OutputFile,
  825. OS))
  826. return 0;
  827. if (!CI.getFrontendOpts().RelocatablePCH)
  828. Sysroot.clear();
  829. CI.getPreprocessor().addPPCallbacks(
  830. new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
  831. return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
  832. OS);
  833. }
  834. virtual bool hasCodeCompletionSupport() const { return false; }
  835. virtual bool hasASTFileSupport() const { return false; }
  836. virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
  837. };
  838. }
  839. /// Parse the source file into a translation unit using the given compiler
  840. /// invocation, replacing the current translation unit.
  841. ///
  842. /// \returns True if a failure occurred that causes the ASTUnit not to
  843. /// contain any translation-unit information, false otherwise.
  844. bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
  845. delete SavedMainFileBuffer;
  846. SavedMainFileBuffer = 0;
  847. if (!Invocation) {
  848. delete OverrideMainBuffer;
  849. return true;
  850. }
  851. // Create the compiler instance to use for building the AST.
  852. llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
  853. // Recover resources if we crash before exiting this method.
  854. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  855. CICleanup(Clang.get());
  856. llvm::IntrusiveRefCntPtr<CompilerInvocation>
  857. CCInvocation(new CompilerInvocation(*Invocation));
  858. Clang->setInvocation(CCInvocation.getPtr());
  859. OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
  860. // Set up diagnostics, capturing any diagnostics that would
  861. // otherwise be dropped.
  862. Clang->setDiagnostics(&getDiagnostics());
  863. // Create the target instance.
  864. Clang->getTargetOpts().Features = TargetFeatures;
  865. Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
  866. Clang->getTargetOpts()));
  867. if (!Clang->hasTarget()) {
  868. delete OverrideMainBuffer;
  869. return true;
  870. }
  871. // Inform the target of the language options.
  872. //
  873. // FIXME: We shouldn't need to do this, the target should be immutable once
  874. // created. This complexity should be lifted elsewhere.
  875. Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
  876. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  877. "Invocation must have exactly one source file!");
  878. assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
  879. "FIXME: AST inputs not yet supported here!");
  880. assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
  881. "IR inputs not support here!");
  882. // Configure the various subsystems.
  883. // FIXME: Should we retain the previous file manager?
  884. LangOpts = &Clang->getLangOpts();
  885. FileSystemOpts = Clang->getFileSystemOpts();
  886. FileMgr = new FileManager(FileSystemOpts);
  887. SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
  888. TheSema.reset();
  889. Ctx = 0;
  890. PP = 0;
  891. Reader = 0;
  892. // Clear out old caches and data.
  893. TopLevelDecls.clear();
  894. clearFileLevelDecls();
  895. CleanTemporaryFiles();
  896. if (!OverrideMainBuffer) {
  897. StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
  898. TopLevelDeclsInPreamble.clear();
  899. }
  900. // Create a file manager object to provide access to and cache the filesystem.
  901. Clang->setFileManager(&getFileManager());
  902. // Create the source manager.
  903. Clang->setSourceManager(&getSourceManager());
  904. // If the main file has been overridden due to the use of a preamble,
  905. // make that override happen and introduce the preamble.
  906. PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
  907. PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
  908. = NestedMacroExpansions;
  909. if (OverrideMainBuffer) {
  910. PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
  911. PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
  912. PreprocessorOpts.PrecompiledPreambleBytes.second
  913. = PreambleEndsAtStartOfLine;
  914. PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
  915. PreprocessorOpts.DisablePCHValidation = true;
  916. // The stored diagnostic has the old source manager in it; update
  917. // the locations to refer into the new source manager. Since we've
  918. // been careful to make sure that the source manager's state
  919. // before and after are identical, so that we can reuse the source
  920. // location itself.
  921. for (unsigned I = NumStoredDiagnosticsFromDriver,
  922. N = StoredDiagnostics.size();
  923. I < N; ++I) {
  924. FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
  925. getSourceManager());
  926. StoredDiagnostics[I].setLocation(Loc);
  927. }
  928. // Keep track of the override buffer;
  929. SavedMainFileBuffer = OverrideMainBuffer;
  930. }
  931. llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
  932. new TopLevelDeclTrackerAction(*this));
  933. // Recover resources if we crash before exiting this method.
  934. llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
  935. ActCleanup(Act.get());
  936. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
  937. Clang->getFrontendOpts().Inputs[0].first))
  938. goto error;
  939. if (OverrideMainBuffer) {
  940. std::string ModName = getPreambleFile(this);
  941. TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
  942. getSourceManager(), PreambleDiagnostics,
  943. StoredDiagnostics);
  944. }
  945. Act->Execute();
  946. // Steal the created target, context, and preprocessor.
  947. TheSema.reset(Clang->takeSema());
  948. Consumer.reset(Clang->takeASTConsumer());
  949. Ctx = &Clang->getASTContext();
  950. PP = &Clang->getPreprocessor();
  951. Clang->setSourceManager(0);
  952. Clang->setFileManager(0);
  953. Target = &Clang->getTarget();
  954. Reader = Clang->getModuleManager();
  955. Act->EndSourceFile();
  956. return false;
  957. error:
  958. // Remove the overridden buffer we used for the preamble.
  959. if (OverrideMainBuffer) {
  960. delete OverrideMainBuffer;
  961. SavedMainFileBuffer = 0;
  962. }
  963. StoredDiagnostics.clear();
  964. NumStoredDiagnosticsFromDriver = 0;
  965. return true;
  966. }
  967. /// \brief Simple function to retrieve a path for a preamble precompiled header.
  968. static std::string GetPreamblePCHPath() {
  969. // FIXME: This is lame; sys::Path should provide this function (in particular,
  970. // it should know how to find the temporary files dir).
  971. // FIXME: This is really lame. I copied this code from the Driver!
  972. // FIXME: This is a hack so that we can override the preamble file during
  973. // crash-recovery testing, which is the only case where the preamble files
  974. // are not necessarily cleaned up.
  975. const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
  976. if (TmpFile)
  977. return TmpFile;
  978. std::string Error;
  979. const char *TmpDir = ::getenv("TMPDIR");
  980. if (!TmpDir)
  981. TmpDir = ::getenv("TEMP");
  982. if (!TmpDir)
  983. TmpDir = ::getenv("TMP");
  984. #ifdef LLVM_ON_WIN32
  985. if (!TmpDir)
  986. TmpDir = ::getenv("USERPROFILE");
  987. #endif
  988. if (!TmpDir)
  989. TmpDir = "/tmp";
  990. llvm::sys::Path P(TmpDir);
  991. P.createDirectoryOnDisk(true);
  992. P.appendComponent("preamble");
  993. P.appendSuffix("pch");
  994. if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
  995. return std::string();
  996. return P.str();
  997. }
  998. /// \brief Compute the preamble for the main file, providing the source buffer
  999. /// that corresponds to the main file along with a pair (bytes, start-of-line)
  1000. /// that describes the preamble.
  1001. std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
  1002. ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
  1003. unsigned MaxLines, bool &CreatedBuffer) {
  1004. FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
  1005. PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
  1006. CreatedBuffer = false;
  1007. // Try to determine if the main file has been remapped, either from the
  1008. // command line (to another file) or directly through the compiler invocation
  1009. // (to a memory buffer).
  1010. llvm::MemoryBuffer *Buffer = 0;
  1011. llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
  1012. if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
  1013. // Check whether there is a file-file remapping of the main file
  1014. for (PreprocessorOptions::remapped_file_iterator
  1015. M = PreprocessorOpts.remapped_file_begin(),
  1016. E = PreprocessorOpts.remapped_file_end();
  1017. M != E;
  1018. ++M) {
  1019. llvm::sys::PathWithStatus MPath(M->first);
  1020. if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
  1021. if (MainFileStatus->uniqueID == MStatus->uniqueID) {
  1022. // We found a remapping. Try to load the resulting, remapped source.
  1023. if (CreatedBuffer) {
  1024. delete Buffer;
  1025. CreatedBuffer = false;
  1026. }
  1027. Buffer = getBufferForFile(M->second);
  1028. if (!Buffer)
  1029. return std::make_pair((llvm::MemoryBuffer*)0,
  1030. std::make_pair(0, true));
  1031. CreatedBuffer = true;
  1032. }
  1033. }
  1034. }
  1035. // Check whether there is a file-buffer remapping. It supercedes the
  1036. // file-file remapping.
  1037. for (PreprocessorOptions::remapped_file_buffer_iterator
  1038. M = PreprocessorOpts.remapped_file_buffer_begin(),
  1039. E = PreprocessorOpts.remapped_file_buffer_end();
  1040. M != E;
  1041. ++M) {
  1042. llvm::sys::PathWithStatus MPath(M->first);
  1043. if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
  1044. if (MainFileStatus->uniqueID == MStatus->uniqueID) {
  1045. // We found a remapping.
  1046. if (CreatedBuffer) {
  1047. delete Buffer;
  1048. CreatedBuffer = false;
  1049. }
  1050. Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
  1051. }
  1052. }
  1053. }
  1054. }
  1055. // If the main source file was not remapped, load it now.
  1056. if (!Buffer) {
  1057. Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
  1058. if (!Buffer)
  1059. return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
  1060. CreatedBuffer = true;
  1061. }
  1062. return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
  1063. *Invocation.getLangOpts(),
  1064. MaxLines));
  1065. }
  1066. static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
  1067. unsigned NewSize,
  1068. StringRef NewName) {
  1069. llvm::MemoryBuffer *Result
  1070. = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
  1071. memcpy(const_cast<char*>(Result->getBufferStart()),
  1072. Old->getBufferStart(), Old->getBufferSize());
  1073. memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
  1074. ' ', NewSize - Old->getBufferSize() - 1);
  1075. const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
  1076. return Result;
  1077. }
  1078. /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
  1079. /// the source file.
  1080. ///
  1081. /// This routine will compute the preamble of the main source file. If a
  1082. /// non-trivial preamble is found, it will precompile that preamble into a
  1083. /// precompiled header so that the precompiled preamble can be used to reduce
  1084. /// reparsing time. If a precompiled preamble has already been constructed,
  1085. /// this routine will determine if it is still valid and, if so, avoid
  1086. /// rebuilding the precompiled preamble.
  1087. ///
  1088. /// \param AllowRebuild When true (the default), this routine is
  1089. /// allowed to rebuild the precompiled preamble if it is found to be
  1090. /// out-of-date.
  1091. ///
  1092. /// \param MaxLines When non-zero, the maximum number of lines that
  1093. /// can occur within the preamble.
  1094. ///
  1095. /// \returns If the precompiled preamble can be used, returns a newly-allocated
  1096. /// buffer that should be used in place of the main file when doing so.
  1097. /// Otherwise, returns a NULL pointer.
  1098. llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
  1099. const CompilerInvocation &PreambleInvocationIn,
  1100. bool AllowRebuild,
  1101. unsigned MaxLines) {
  1102. llvm::IntrusiveRefCntPtr<CompilerInvocation>
  1103. PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
  1104. FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
  1105. PreprocessorOptions &PreprocessorOpts
  1106. = PreambleInvocation->getPreprocessorOpts();
  1107. bool CreatedPreambleBuffer = false;
  1108. std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
  1109. = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
  1110. // If ComputePreamble() Take ownership of the preamble buffer.
  1111. llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
  1112. if (CreatedPreambleBuffer)
  1113. OwnedPreambleBuffer.reset(NewPreamble.first);
  1114. if (!NewPreamble.second.first) {
  1115. // We couldn't find a preamble in the main source. Clear out the current
  1116. // preamble, if we have one. It's obviously no good any more.
  1117. Preamble.clear();
  1118. erasePreambleFile(this);
  1119. // The next time we actually see a preamble, precompile it.
  1120. PreambleRebuildCounter = 1;
  1121. return 0;
  1122. }
  1123. if (!Preamble.empty()) {
  1124. // We've previously computed a preamble. Check whether we have the same
  1125. // preamble now that we did before, and that there's enough space in
  1126. // the main-file buffer within the precompiled preamble to fit the
  1127. // new main file.
  1128. if (Preamble.size() == NewPreamble.second.first &&
  1129. PreambleEndsAtStartOfLine == NewPreamble.second.second &&
  1130. NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
  1131. memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
  1132. NewPreamble.second.first) == 0) {
  1133. // The preamble has not changed. We may be able to re-use the precompiled
  1134. // preamble.
  1135. // Check that none of the files used by the preamble have changed.
  1136. bool AnyFileChanged = false;
  1137. // First, make a record of those files that have been overridden via
  1138. // remapping or unsaved_files.
  1139. llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
  1140. for (PreprocessorOptions::remapped_file_iterator
  1141. R = PreprocessorOpts.remapped_file_begin(),
  1142. REnd = PreprocessorOpts.remapped_file_end();
  1143. !AnyFileChanged && R != REnd;
  1144. ++R) {
  1145. struct stat StatBuf;
  1146. if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
  1147. // If we can't stat the file we're remapping to, assume that something
  1148. // horrible happened.
  1149. AnyFileChanged = true;
  1150. break;
  1151. }
  1152. OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
  1153. StatBuf.st_mtime);
  1154. }
  1155. for (PreprocessorOptions::remapped_file_buffer_iterator
  1156. R = PreprocessorOpts.remapped_file_buffer_begin(),
  1157. REnd = PreprocessorOpts.remapped_file_buffer_end();
  1158. !AnyFileChanged && R != REnd;
  1159. ++R) {
  1160. // FIXME: Should we actually compare the contents of file->buffer
  1161. // remappings?
  1162. OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
  1163. 0);
  1164. }
  1165. // Check whether anything has changed.
  1166. for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
  1167. F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
  1168. !AnyFileChanged && F != FEnd;
  1169. ++F) {
  1170. llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
  1171. = OverriddenFiles.find(F->first());
  1172. if (Overridden != OverriddenFiles.end()) {
  1173. // This file was remapped; check whether the newly-mapped file
  1174. // matches up with the previous mapping.
  1175. if (Overridden->second != F->second)
  1176. AnyFileChanged = true;
  1177. continue;
  1178. }
  1179. // The file was not remapped; check whether it has changed on disk.
  1180. struct stat StatBuf;
  1181. if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
  1182. // If we can't stat the file, assume that something horrible happened.
  1183. AnyFileChanged = true;
  1184. } else if (StatBuf.st_size != F->second.first ||
  1185. StatBuf.st_mtime != F->second.second)
  1186. AnyFileChanged = true;
  1187. }
  1188. if (!AnyFileChanged) {
  1189. // Okay! We can re-use the precompiled preamble.
  1190. // Set the state of the diagnostic object to mimic its state
  1191. // after parsing the preamble.
  1192. getDiagnostics().Reset();
  1193. ProcessWarningOptions(getDiagnostics(),
  1194. PreambleInvocation->getDiagnosticOpts());
  1195. getDiagnostics().setNumWarnings(NumWarningsInPreamble);
  1196. // Create a version of the main file buffer that is padded to
  1197. // buffer size we reserved when creating the preamble.
  1198. return CreatePaddedMainFileBuffer(NewPreamble.first,
  1199. PreambleReservedSize,
  1200. FrontendOpts.Inputs[0].second);
  1201. }
  1202. }
  1203. // If we aren't allowed to rebuild the precompiled preamble, just
  1204. // return now.
  1205. if (!AllowRebuild)
  1206. return 0;
  1207. // We can't reuse the previously-computed preamble. Build a new one.
  1208. Preamble.clear();
  1209. PreambleDiagnostics.clear();
  1210. erasePreambleFile(this);
  1211. PreambleRebuildCounter = 1;
  1212. } else if (!AllowRebuild) {
  1213. // We aren't allowed to rebuild the precompiled preamble; just
  1214. // return now.
  1215. return 0;
  1216. }
  1217. // If the preamble rebuild counter > 1, it's because we previously
  1218. // failed to build a preamble and we're not yet ready to try
  1219. // again. Decrement the counter and return a failure.
  1220. if (PreambleRebuildCounter > 1) {
  1221. --PreambleRebuildCounter;
  1222. return 0;
  1223. }
  1224. // Create a temporary file for the precompiled preamble. In rare
  1225. // circumstances, this can fail.
  1226. std::string PreamblePCHPath = GetPreamblePCHPath();
  1227. if (PreamblePCHPath.empty()) {
  1228. // Try again next time.
  1229. PreambleRebuildCounter = 1;
  1230. return 0;
  1231. }
  1232. // We did not previously compute a preamble, or it can't be reused anyway.
  1233. SimpleTimer PreambleTimer(WantTiming);
  1234. PreambleTimer.setOutput("Precompiling preamble");
  1235. // Create a new buffer that stores the preamble. The buffer also contains
  1236. // extra space for the original contents of the file (which will be present
  1237. // when we actually parse the file) along with more room in case the file
  1238. // grows.
  1239. PreambleReservedSize = NewPreamble.first->getBufferSize();
  1240. if (PreambleReservedSize < 4096)
  1241. PreambleReservedSize = 8191;
  1242. else
  1243. PreambleReservedSize *= 2;
  1244. // Save the preamble text for later; we'll need to compare against it for
  1245. // subsequent reparses.
  1246. StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
  1247. Preamble.assign(FileMgr->getFile(MainFilename),
  1248. NewPreamble.first->getBufferStart(),
  1249. NewPreamble.first->getBufferStart()
  1250. + NewPreamble.second.first);
  1251. PreambleEndsAtStartOfLine = NewPreamble.second.second;
  1252. delete PreambleBuffer;
  1253. PreambleBuffer
  1254. = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
  1255. FrontendOpts.Inputs[0].second);
  1256. memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
  1257. NewPreamble.first->getBufferStart(), Preamble.size());
  1258. memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
  1259. ' ', PreambleReservedSize - Preamble.size() - 1);
  1260. const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
  1261. // Remap the main source file to the preamble buffer.
  1262. llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
  1263. PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
  1264. // Tell the compiler invocation to generate a temporary precompiled header.
  1265. FrontendOpts.ProgramAction = frontend::GeneratePCH;
  1266. // FIXME: Generate the precompiled header into memory?
  1267. FrontendOpts.OutputFile = PreamblePCHPath;
  1268. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  1269. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  1270. // Create the compiler instance to use for building the precompiled preamble.
  1271. llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
  1272. // Recover resources if we crash before exiting this method.
  1273. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  1274. CICleanup(Clang.get());
  1275. Clang->setInvocation(&*PreambleInvocation);
  1276. OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
  1277. // Set up diagnostics, capturing all of the diagnostics produced.
  1278. Clang->setDiagnostics(&getDiagnostics());
  1279. // Create the target instance.
  1280. Clang->getTargetOpts().Features = TargetFeatures;
  1281. Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
  1282. Clang->getTargetOpts()));
  1283. if (!Clang->hasTarget()) {
  1284. llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
  1285. Preamble.clear();
  1286. PreambleRebuildCounter = DefaultPreambleRebuildInterval;
  1287. PreprocessorOpts.eraseRemappedFile(
  1288. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1289. return 0;
  1290. }
  1291. // Inform the target of the language options.
  1292. //
  1293. // FIXME: We shouldn't need to do this, the target should be immutable once
  1294. // created. This complexity should be lifted elsewhere.
  1295. Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
  1296. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1297. "Invocation must have exactly one source file!");
  1298. assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
  1299. "FIXME: AST inputs not yet supported here!");
  1300. assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
  1301. "IR inputs not support here!");
  1302. // Clear out old caches and data.
  1303. getDiagnostics().Reset();
  1304. ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
  1305. StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
  1306. TopLevelDecls.clear();
  1307. TopLevelDeclsInPreamble.clear();
  1308. // Create a file manager object to provide access to and cache the filesystem.
  1309. Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
  1310. // Create the source manager.
  1311. Clang->setSourceManager(new SourceManager(getDiagnostics(),
  1312. Clang->getFileManager()));
  1313. llvm::OwningPtr<PrecompilePreambleAction> Act;
  1314. Act.reset(new PrecompilePreambleAction(*this));
  1315. if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
  1316. Clang->getFrontendOpts().Inputs[0].first)) {
  1317. llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
  1318. Preamble.clear();
  1319. PreambleRebuildCounter = DefaultPreambleRebuildInterval;
  1320. PreprocessorOpts.eraseRemappedFile(
  1321. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1322. return 0;
  1323. }
  1324. Act->Execute();
  1325. Act->EndSourceFile();
  1326. if (Diagnostics->hasErrorOccurred()) {
  1327. // There were errors parsing the preamble, so no precompiled header was
  1328. // generated. Forget that we even tried.
  1329. // FIXME: Should we leave a note for ourselves to try again?
  1330. llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
  1331. Preamble.clear();
  1332. TopLevelDeclsInPreamble.clear();
  1333. PreambleRebuildCounter = DefaultPreambleRebuildInterval;
  1334. PreprocessorOpts.eraseRemappedFile(
  1335. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1336. return 0;
  1337. }
  1338. // Transfer any diagnostics generated when parsing the preamble into the set
  1339. // of preamble diagnostics.
  1340. PreambleDiagnostics.clear();
  1341. PreambleDiagnostics.insert(PreambleDiagnostics.end(),
  1342. stored_diag_afterDriver_begin(), stored_diag_end());
  1343. StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
  1344. // Keep track of the preamble we precompiled.
  1345. setPreambleFile(this, FrontendOpts.OutputFile);
  1346. NumWarningsInPreamble = getDiagnostics().getNumWarnings();
  1347. // Keep track of all of the files that the source manager knows about,
  1348. // so we can verify whether they have changed or not.
  1349. FilesInPreamble.clear();
  1350. SourceManager &SourceMgr = Clang->getSourceManager();
  1351. const llvm::MemoryBuffer *MainFileBuffer
  1352. = SourceMgr.getBuffer(SourceMgr.getMainFileID());
  1353. for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
  1354. FEnd = SourceMgr.fileinfo_end();
  1355. F != FEnd;
  1356. ++F) {
  1357. const FileEntry *File = F->second->OrigEntry;
  1358. if (!File || F->second->getRawBuffer() == MainFileBuffer)
  1359. continue;
  1360. FilesInPreamble[File->getName()]
  1361. = std::make_pair(F->second->getSize(), File->getModificationTime());
  1362. }
  1363. PreambleRebuildCounter = 1;
  1364. PreprocessorOpts.eraseRemappedFile(
  1365. PreprocessorOpts.remapped_file_buffer_end() - 1);
  1366. // If the hash of top-level entities differs from the hash of the top-level
  1367. // entities the last time we rebuilt the preamble, clear out the completion
  1368. // cache.
  1369. if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
  1370. CompletionCacheTopLevelHashValue = 0;
  1371. PreambleTopLevelHashValue = CurrentTopLevelHashValue;
  1372. }
  1373. return CreatePaddedMainFileBuffer(NewPreamble.first,
  1374. PreambleReservedSize,
  1375. FrontendOpts.Inputs[0].second);
  1376. }
  1377. void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
  1378. std::vector<Decl *> Resolved;
  1379. Resolved.reserve(TopLevelDeclsInPreamble.size());
  1380. ExternalASTSource &Source = *getASTContext().getExternalSource();
  1381. for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
  1382. // Resolve the declaration ID to an actual declaration, possibly
  1383. // deserializing the declaration in the process.
  1384. Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
  1385. if (D)
  1386. Resolved.push_back(D);
  1387. }
  1388. TopLevelDeclsInPreamble.clear();
  1389. TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
  1390. }
  1391. StringRef ASTUnit::getMainFileName() const {
  1392. return Invocation->getFrontendOpts().Inputs[0].second;
  1393. }
  1394. ASTUnit *ASTUnit::create(CompilerInvocation *CI,
  1395. llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  1396. bool CaptureDiagnostics) {
  1397. llvm::OwningPtr<ASTUnit> AST;
  1398. AST.reset(new ASTUnit(false));
  1399. ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
  1400. AST->Diagnostics = Diags;
  1401. AST->Invocation = CI;
  1402. AST->FileSystemOpts = CI->getFileSystemOpts();
  1403. AST->FileMgr = new FileManager(AST->FileSystemOpts);
  1404. AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
  1405. return AST.take();
  1406. }
  1407. ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
  1408. llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  1409. ASTFrontendAction *Action,
  1410. ASTUnit *Unit,
  1411. bool Persistent,
  1412. StringRef ResourceFilesPath,
  1413. bool OnlyLocalDecls,
  1414. bool CaptureDiagnostics,
  1415. bool PrecompilePreamble,
  1416. bool CacheCodeCompletionResults) {
  1417. assert(CI && "A CompilerInvocation is required");
  1418. llvm::OwningPtr<ASTUnit> OwnAST;
  1419. ASTUnit *AST = Unit;
  1420. if (!AST) {
  1421. // Create the AST unit.
  1422. OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
  1423. AST = OwnAST.get();
  1424. }
  1425. if (!ResourceFilesPath.empty()) {
  1426. // Override the resources path.
  1427. CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
  1428. }
  1429. AST->OnlyLocalDecls = OnlyLocalDecls;
  1430. AST->CaptureDiagnostics = CaptureDiagnostics;
  1431. if (PrecompilePreamble)
  1432. AST->PreambleRebuildCounter = 2;
  1433. AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
  1434. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1435. // Recover resources if we crash before exiting this method.
  1436. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1437. ASTUnitCleanup(OwnAST.get());
  1438. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  1439. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
  1440. DiagCleanup(Diags.getPtr());
  1441. // We'll manage file buffers ourselves.
  1442. CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
  1443. CI->getFrontendOpts().DisableFree = false;
  1444. ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
  1445. // Save the target features.
  1446. AST->TargetFeatures = CI->getTargetOpts().Features;
  1447. // Create the compiler instance to use for building the AST.
  1448. llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
  1449. // Recover resources if we crash before exiting this method.
  1450. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  1451. CICleanup(Clang.get());
  1452. Clang->setInvocation(CI);
  1453. AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
  1454. // Set up diagnostics, capturing any diagnostics that would
  1455. // otherwise be dropped.
  1456. Clang->setDiagnostics(&AST->getDiagnostics());
  1457. // Create the target instance.
  1458. Clang->getTargetOpts().Features = AST->TargetFeatures;
  1459. Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
  1460. Clang->getTargetOpts()));
  1461. if (!Clang->hasTarget())
  1462. return 0;
  1463. // Inform the target of the language options.
  1464. //
  1465. // FIXME: We shouldn't need to do this, the target should be immutable once
  1466. // created. This complexity should be lifted elsewhere.
  1467. Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
  1468. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1469. "Invocation must have exactly one source file!");
  1470. assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
  1471. "FIXME: AST inputs not yet supported here!");
  1472. assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
  1473. "IR inputs not supported here!");
  1474. // Configure the various subsystems.
  1475. AST->TheSema.reset();
  1476. AST->Ctx = 0;
  1477. AST->PP = 0;
  1478. AST->Reader = 0;
  1479. // Create a file manager object to provide access to and cache the filesystem.
  1480. Clang->setFileManager(&AST->getFileManager());
  1481. // Create the source manager.
  1482. Clang->setSourceManager(&AST->getSourceManager());
  1483. ASTFrontendAction *Act = Action;
  1484. llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
  1485. if (!Act) {
  1486. TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
  1487. Act = TrackerAct.get();
  1488. }
  1489. // Recover resources if we crash before exiting this method.
  1490. llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
  1491. ActCleanup(TrackerAct.get());
  1492. if (!Act->BeginSourceFile(*Clang.get(),
  1493. Clang->getFrontendOpts().Inputs[0].second,
  1494. Clang->getFrontendOpts().Inputs[0].first))
  1495. return 0;
  1496. if (Persistent && !TrackerAct) {
  1497. Clang->getPreprocessor().addPPCallbacks(
  1498. new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
  1499. std::vector<ASTConsumer*> Consumers;
  1500. if (Clang->hasASTConsumer())
  1501. Consumers.push_back(Clang->takeASTConsumer());
  1502. Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
  1503. AST->getCurrentTopLevelHashValue()));
  1504. Clang->setASTConsumer(new MultiplexConsumer(Consumers));
  1505. }
  1506. Act->Execute();
  1507. // Steal the created target, context, and preprocessor.
  1508. AST->TheSema.reset(Clang->takeSema());
  1509. AST->Consumer.reset(Clang->takeASTConsumer());
  1510. AST->Ctx = &Clang->getASTContext();
  1511. AST->PP = &Clang->getPreprocessor();
  1512. Clang->setSourceManager(0);
  1513. Clang->setFileManager(0);
  1514. AST->Target = &Clang->getTarget();
  1515. AST->Reader = Clang->getModuleManager();
  1516. Act->EndSourceFile();
  1517. if (OwnAST)
  1518. return OwnAST.take();
  1519. else
  1520. return AST;
  1521. }
  1522. bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
  1523. if (!Invocation)
  1524. return true;
  1525. // We'll manage file buffers ourselves.
  1526. Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
  1527. Invocation->getFrontendOpts().DisableFree = false;
  1528. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1529. // Save the target features.
  1530. TargetFeatures = Invocation->getTargetOpts().Features;
  1531. llvm::MemoryBuffer *OverrideMainBuffer = 0;
  1532. if (PrecompilePreamble) {
  1533. PreambleRebuildCounter = 2;
  1534. OverrideMainBuffer
  1535. = getMainBufferWithPrecompiledPreamble(*Invocation);
  1536. }
  1537. SimpleTimer ParsingTimer(WantTiming);
  1538. ParsingTimer.setOutput("Parsing " + getMainFileName());
  1539. // Recover resources if we crash before exiting this method.
  1540. llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
  1541. MemBufferCleanup(OverrideMainBuffer);
  1542. return Parse(OverrideMainBuffer);
  1543. }
  1544. ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
  1545. llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  1546. bool OnlyLocalDecls,
  1547. bool CaptureDiagnostics,
  1548. bool PrecompilePreamble,
  1549. TranslationUnitKind TUKind,
  1550. bool CacheCodeCompletionResults,
  1551. bool NestedMacroExpansions) {
  1552. // Create the AST unit.
  1553. llvm::OwningPtr<ASTUnit> AST;
  1554. AST.reset(new ASTUnit(false));
  1555. ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
  1556. AST->Diagnostics = Diags;
  1557. AST->OnlyLocalDecls = OnlyLocalDecls;
  1558. AST->CaptureDiagnostics = CaptureDiagnostics;
  1559. AST->TUKind = TUKind;
  1560. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1561. AST->Invocation = CI;
  1562. AST->NestedMacroExpansions = NestedMacroExpansions;
  1563. // Recover resources if we crash before exiting this method.
  1564. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1565. ASTUnitCleanup(AST.get());
  1566. llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
  1567. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
  1568. DiagCleanup(Diags.getPtr());
  1569. return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
  1570. }
  1571. ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
  1572. const char **ArgEnd,
  1573. llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
  1574. StringRef ResourceFilesPath,
  1575. bool OnlyLocalDecls,
  1576. bool CaptureDiagnostics,
  1577. RemappedFile *RemappedFiles,
  1578. unsigned NumRemappedFiles,
  1579. bool RemappedFilesKeepOriginalName,
  1580. bool PrecompilePreamble,
  1581. TranslationUnitKind TUKind,
  1582. bool CacheCodeCompletionResults,
  1583. bool NestedMacroExpansions) {
  1584. if (!Diags.getPtr()) {
  1585. // No diagnostics engine was provided, so create our own diagnostics object
  1586. // with the default options.
  1587. DiagnosticOptions DiagOpts;
  1588. Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
  1589. ArgBegin);
  1590. }
  1591. SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
  1592. llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
  1593. {
  1594. CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
  1595. StoredDiagnostics);
  1596. CI = clang::createInvocationFromCommandLine(
  1597. llvm::makeArrayRef(ArgBegin, ArgEnd),
  1598. Diags);
  1599. if (!CI)
  1600. return 0;
  1601. }
  1602. // Override any files that need remapping
  1603. for (unsigned I = 0; I != NumRemappedFiles; ++I) {
  1604. FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
  1605. if (const llvm::MemoryBuffer *
  1606. memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
  1607. CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
  1608. } else {
  1609. const char *fname = fileOrBuf.get<const char *>();
  1610. CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
  1611. }
  1612. }
  1613. CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
  1614. RemappedFilesKeepOriginalName;
  1615. // Override the resources path.
  1616. CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
  1617. // Create the AST unit.
  1618. llvm::OwningPtr<ASTUnit> AST;
  1619. AST.reset(new ASTUnit(false));
  1620. ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
  1621. AST->Diagnostics = Diags;
  1622. Diags = 0; // Zero out now to ease cleanup during crash recovery.
  1623. AST->FileSystemOpts = CI->getFileSystemOpts();
  1624. AST->FileMgr = new FileManager(AST->FileSystemOpts);
  1625. AST->OnlyLocalDecls = OnlyLocalDecls;
  1626. AST->CaptureDiagnostics = CaptureDiagnostics;
  1627. AST->TUKind = TUKind;
  1628. AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
  1629. AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
  1630. AST->StoredDiagnostics.swap(StoredDiagnostics);
  1631. AST->Invocation = CI;
  1632. CI = 0; // Zero out now to ease cleanup during crash recovery.
  1633. AST->NestedMacroExpansions = NestedMacroExpansions;
  1634. // Recover resources if we crash before exiting this method.
  1635. llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
  1636. ASTUnitCleanup(AST.get());
  1637. return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
  1638. }
  1639. bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
  1640. if (!Invocation)
  1641. return true;
  1642. clearFileLevelDecls();
  1643. SimpleTimer ParsingTimer(WantTiming);
  1644. ParsingTimer.setOutput("Reparsing " + getMainFileName());
  1645. // Remap files.
  1646. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  1647. PPOpts.DisableStatCache = true;
  1648. for (PreprocessorOptions::remapped_file_buffer_iterator
  1649. R = PPOpts.remapped_file_buffer_begin(),
  1650. REnd = PPOpts.remapped_file_buffer_end();
  1651. R != REnd;
  1652. ++R) {
  1653. delete R->second;
  1654. }
  1655. Invocation->getPreprocessorOpts().clearRemappedFiles();
  1656. for (unsigned I = 0; I != NumRemappedFiles; ++I) {
  1657. FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
  1658. if (const llvm::MemoryBuffer *
  1659. memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
  1660. Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
  1661. memBuf);
  1662. } else {
  1663. const char *fname = fileOrBuf.get<const char *>();
  1664. Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
  1665. fname);
  1666. }
  1667. }
  1668. // If we have a preamble file lying around, or if we might try to
  1669. // build a precompiled preamble, do so now.
  1670. llvm::MemoryBuffer *OverrideMainBuffer = 0;
  1671. if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
  1672. OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
  1673. // Clear out the diagnostics state.
  1674. getDiagnostics().Reset();
  1675. ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
  1676. if (OverrideMainBuffer)
  1677. getDiagnostics().setNumWarnings(NumWarningsInPreamble);
  1678. // Parse the sources
  1679. bool Result = Parse(OverrideMainBuffer);
  1680. // If we're caching global code-completion results, and the top-level
  1681. // declarations have changed, clear out the code-completion cache.
  1682. if (!Result && ShouldCacheCodeCompletionResults &&
  1683. CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
  1684. CacheCodeCompletionResults();
  1685. // We now need to clear out the completion allocator for
  1686. // clang_getCursorCompletionString; it'll be recreated if necessary.
  1687. CursorCompletionAllocator = 0;
  1688. return Result;
  1689. }
  1690. //----------------------------------------------------------------------------//
  1691. // Code completion
  1692. //----------------------------------------------------------------------------//
  1693. namespace {
  1694. /// \brief Code completion consumer that combines the cached code-completion
  1695. /// results from an ASTUnit with the code-completion results provided to it,
  1696. /// then passes the result on to
  1697. class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
  1698. unsigned long long NormalContexts;
  1699. ASTUnit &AST;
  1700. CodeCompleteConsumer &Next;
  1701. public:
  1702. AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
  1703. bool IncludeMacros, bool IncludeCodePatterns,
  1704. bool IncludeGlobals)
  1705. : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
  1706. Next.isOutputBinary()), AST(AST), Next(Next)
  1707. {
  1708. // Compute the set of contexts in which we will look when we don't have
  1709. // any information about the specific context.
  1710. NormalContexts
  1711. = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
  1712. | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
  1713. | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
  1714. | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
  1715. | (1LL << (CodeCompletionContext::CCC_Statement - 1))
  1716. | (1LL << (CodeCompletionContext::CCC_Expression - 1))
  1717. | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
  1718. | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
  1719. | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
  1720. | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
  1721. | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
  1722. | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
  1723. | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
  1724. if (AST.getASTContext().getLangOptions().CPlusPlus)
  1725. NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
  1726. | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
  1727. | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
  1728. }
  1729. virtual void ProcessCodeCompleteResults(Sema &S,
  1730. CodeCompletionContext Context,
  1731. CodeCompletionResult *Results,
  1732. unsigned NumResults);
  1733. virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
  1734. OverloadCandidate *Candidates,
  1735. unsigned NumCandidates) {
  1736. Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
  1737. }
  1738. virtual CodeCompletionAllocator &getAllocator() {
  1739. return Next.getAllocator();
  1740. }
  1741. };
  1742. }
  1743. /// \brief Helper function that computes which global names are hidden by the
  1744. /// local code-completion results.
  1745. static void CalculateHiddenNames(const CodeCompletionContext &Context,
  1746. CodeCompletionResult *Results,
  1747. unsigned NumResults,
  1748. ASTContext &Ctx,
  1749. llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
  1750. bool OnlyTagNames = false;
  1751. switch (Context.getKind()) {
  1752. case CodeCompletionContext::CCC_Recovery:
  1753. case CodeCompletionContext::CCC_TopLevel:
  1754. case CodeCompletionContext::CCC_ObjCInterface:
  1755. case CodeCompletionContext::CCC_ObjCImplementation:
  1756. case CodeCompletionContext::CCC_ObjCIvarList:
  1757. case CodeCompletionContext::CCC_ClassStructUnion:
  1758. case CodeCompletionContext::CCC_Statement:
  1759. case CodeCompletionContext::CCC_Expression:
  1760. case CodeCompletionContext::CCC_ObjCMessageReceiver:
  1761. case CodeCompletionContext::CCC_DotMemberAccess:
  1762. case CodeCompletionContext::CCC_ArrowMemberAccess:
  1763. case CodeCompletionContext::CCC_ObjCPropertyAccess:
  1764. case CodeCompletionContext::CCC_Namespace:
  1765. case CodeCompletionContext::CCC_Type:
  1766. case CodeCompletionContext::CCC_Name:
  1767. case CodeCompletionContext::CCC_PotentiallyQualifiedName:
  1768. case CodeCompletionContext::CCC_ParenthesizedExpression:
  1769. case CodeCompletionContext::CCC_ObjCInterfaceName:
  1770. break;
  1771. case CodeCompletionContext::CCC_EnumTag:
  1772. case CodeCompletionContext::CCC_UnionTag:
  1773. case CodeCompletionContext::CCC_ClassOrStructTag:
  1774. OnlyTagNames = true;
  1775. break;
  1776. case CodeCompletionContext::CCC_ObjCProtocolName:
  1777. case CodeCompletionContext::CCC_MacroName:
  1778. case CodeCompletionContext::CCC_MacroNameUse:
  1779. case CodeCompletionContext::CCC_PreprocessorExpression:
  1780. case CodeCompletionContext::CCC_PreprocessorDirective:
  1781. case CodeCompletionContext::CCC_NaturalLanguage:
  1782. case CodeCompletionContext::CCC_SelectorName:
  1783. case CodeCompletionContext::CCC_TypeQualifiers:
  1784. case CodeCompletionContext::CCC_Other:
  1785. case CodeCompletionContext::CCC_OtherWithMacros:
  1786. case CodeCompletionContext::CCC_ObjCInstanceMessage:
  1787. case CodeCompletionContext::CCC_ObjCClassMessage:
  1788. case CodeCompletionContext::CCC_ObjCCategoryName:
  1789. // We're looking for nothing, or we're looking for names that cannot
  1790. // be hidden.
  1791. return;
  1792. }
  1793. typedef CodeCompletionResult Result;
  1794. for (unsigned I = 0; I != NumResults; ++I) {
  1795. if (Results[I].Kind != Result::RK_Declaration)
  1796. continue;
  1797. unsigned IDNS
  1798. = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
  1799. bool Hiding = false;
  1800. if (OnlyTagNames)
  1801. Hiding = (IDNS & Decl::IDNS_Tag);
  1802. else {
  1803. unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
  1804. Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
  1805. Decl::IDNS_NonMemberOperator);
  1806. if (Ctx.getLangOptions().CPlusPlus)
  1807. HiddenIDNS |= Decl::IDNS_Tag;
  1808. Hiding = (IDNS & HiddenIDNS);
  1809. }
  1810. if (!Hiding)
  1811. continue;
  1812. DeclarationName Name = Results[I].Declaration->getDeclName();
  1813. if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
  1814. HiddenNames.insert(Identifier->getName());
  1815. else
  1816. HiddenNames.insert(Name.getAsString());
  1817. }
  1818. }
  1819. void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
  1820. CodeCompletionContext Context,
  1821. CodeCompletionResult *Results,
  1822. unsigned NumResults) {
  1823. // Merge the results we were given with the results we cached.
  1824. bool AddedResult = false;
  1825. unsigned InContexts
  1826. = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
  1827. : (1ULL << (Context.getKind() - 1)));
  1828. // Contains the set of names that are hidden by "local" completion results.
  1829. llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
  1830. typedef CodeCompletionResult Result;
  1831. SmallVector<Result, 8> AllResults;
  1832. for (ASTUnit::cached_completion_iterator
  1833. C = AST.cached_completion_begin(),
  1834. CEnd = AST.cached_completion_end();
  1835. C != CEnd; ++C) {
  1836. // If the context we are in matches any of the contexts we are
  1837. // interested in, we'll add this result.
  1838. if ((C->ShowInContexts & InContexts) == 0)
  1839. continue;
  1840. // If we haven't added any results previously, do so now.
  1841. if (!AddedResult) {
  1842. CalculateHiddenNames(Context, Results, NumResults, S.Context,
  1843. HiddenNames);
  1844. AllResults.insert(AllResults.end(), Results, Results + NumResults);
  1845. AddedResult = true;
  1846. }
  1847. // Determine whether this global completion result is hidden by a local
  1848. // completion result. If so, skip it.
  1849. if (C->Kind != CXCursor_MacroDefinition &&
  1850. HiddenNames.count(C->Completion->getTypedText()))
  1851. continue;
  1852. // Adjust priority based on similar type classes.
  1853. unsigned Priority = C->Priority;
  1854. CXCursorKind CursorKind = C->Kind;
  1855. CodeCompletionString *Completion = C->Completion;
  1856. if (!Context.getPreferredType().isNull()) {
  1857. if (C->Kind == CXCursor_MacroDefinition) {
  1858. Priority = getMacroUsagePriority(C->Completion->getTypedText(),
  1859. S.getLangOptions(),
  1860. Context.getPreferredType()->isAnyPointerType());
  1861. } else if (C->Type) {
  1862. CanQualType Expected
  1863. = S.Context.getCanonicalType(
  1864. Context.getPreferredType().getUnqualifiedType());
  1865. SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
  1866. if (ExpectedSTC == C->TypeClass) {
  1867. // We know this type is similar; check for an exact match.
  1868. llvm::StringMap<unsigned> &CachedCompletionTypes
  1869. = AST.getCachedCompletionTypes();
  1870. llvm::StringMap<unsigned>::iterator Pos
  1871. = CachedCompletionTypes.find(QualType(Expected).getAsString());
  1872. if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
  1873. Priority /= CCF_ExactTypeMatch;
  1874. else
  1875. Priority /= CCF_SimilarTypeMatch;
  1876. }
  1877. }
  1878. }
  1879. // Adjust the completion string, if required.
  1880. if (C->Kind == CXCursor_MacroDefinition &&
  1881. Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
  1882. // Create a new code-completion string that just contains the
  1883. // macro name, without its arguments.
  1884. CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
  1885. C->Availability);
  1886. Builder.AddTypedTextChunk(C->Completion->getTypedText());
  1887. CursorKind = CXCursor_NotImplemented;
  1888. Priority = CCP_CodePattern;
  1889. Completion = Builder.TakeString();
  1890. }
  1891. AllResults.push_back(Result(Completion, Priority, CursorKind,
  1892. C->Availability));
  1893. }
  1894. // If we did not add any cached completion results, just forward the
  1895. // results we were given to the next consumer.
  1896. if (!AddedResult) {
  1897. Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
  1898. return;
  1899. }
  1900. Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
  1901. AllResults.size());
  1902. }
  1903. void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
  1904. RemappedFile *RemappedFiles,
  1905. unsigned NumRemappedFiles,
  1906. bool IncludeMacros,
  1907. bool IncludeCodePatterns,
  1908. CodeCompleteConsumer &Consumer,
  1909. DiagnosticsEngine &Diag, LangOptions &LangOpts,
  1910. SourceManager &SourceMgr, FileManager &FileMgr,
  1911. SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
  1912. SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
  1913. if (!Invocation)
  1914. return;
  1915. SimpleTimer CompletionTimer(WantTiming);
  1916. CompletionTimer.setOutput("Code completion @ " + File + ":" +
  1917. Twine(Line) + ":" + Twine(Column));
  1918. llvm::IntrusiveRefCntPtr<CompilerInvocation>
  1919. CCInvocation(new CompilerInvocation(*Invocation));
  1920. FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
  1921. PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
  1922. FrontendOpts.ShowMacrosInCodeCompletion
  1923. = IncludeMacros && CachedCompletionResults.empty();
  1924. FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
  1925. FrontendOpts.ShowGlobalSymbolsInCodeCompletion
  1926. = CachedCompletionResults.empty();
  1927. FrontendOpts.CodeCompletionAt.FileName = File;
  1928. FrontendOpts.CodeCompletionAt.Line = Line;
  1929. FrontendOpts.CodeCompletionAt.Column = Column;
  1930. // Set the language options appropriately.
  1931. LangOpts = *CCInvocation->getLangOpts();
  1932. llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
  1933. // Recover resources if we crash before exiting this method.
  1934. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
  1935. CICleanup(Clang.get());
  1936. Clang->setInvocation(&*CCInvocation);
  1937. OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
  1938. // Set up diagnostics, capturing any diagnostics produced.
  1939. Clang->setDiagnostics(&Diag);
  1940. ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
  1941. CaptureDroppedDiagnostics Capture(true,
  1942. Clang->getDiagnostics(),
  1943. StoredDiagnostics);
  1944. // Create the target instance.
  1945. Clang->getTargetOpts().Features = TargetFeatures;
  1946. Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
  1947. Clang->getTargetOpts()));
  1948. if (!Clang->hasTarget()) {
  1949. Clang->setInvocation(0);
  1950. return;
  1951. }
  1952. // Inform the target of the language options.
  1953. //
  1954. // FIXME: We shouldn't need to do this, the target should be immutable once
  1955. // created. This complexity should be lifted elsewhere.
  1956. Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
  1957. assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  1958. "Invocation must have exactly one source file!");
  1959. assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
  1960. "FIXME: AST inputs not yet supported here!");
  1961. assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
  1962. "IR inputs not support here!");
  1963. // Use the source and file managers that we were given.
  1964. Clang->setFileManager(&FileMgr);
  1965. Clang->setSourceManager(&SourceMgr);
  1966. // Remap files.
  1967. PreprocessorOpts.clearRemappedFiles();
  1968. PreprocessorOpts.RetainRemappedFileBuffers = true;
  1969. for (unsigned I = 0; I != NumRemappedFiles; ++I) {
  1970. FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
  1971. if (const llvm::MemoryBuffer *
  1972. memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
  1973. PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
  1974. OwnedBuffers.push_back(memBuf);
  1975. } else {
  1976. const char *fname = fileOrBuf.get<const char *>();
  1977. PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
  1978. }
  1979. }
  1980. // Use the code completion consumer we were given, but adding any cached
  1981. // code-completion results.
  1982. AugmentedCodeCompleteConsumer *AugmentedConsumer
  1983. = new AugmentedCodeCompleteConsumer(*this, Consumer,
  1984. FrontendOpts.ShowMacrosInCodeCompletion,
  1985. FrontendOpts.ShowCodePatternsInCodeCompletion,
  1986. FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
  1987. Clang->setCodeCompletionConsumer(AugmentedConsumer);
  1988. // If we have a precompiled preamble, try to use it. We only allow
  1989. // the use of the precompiled preamble if we're if the completion
  1990. // point is within the main file, after the end of the precompiled
  1991. // preamble.
  1992. llvm::MemoryBuffer *OverrideMainBuffer = 0;
  1993. if (!getPreambleFile(this).empty()) {
  1994. using llvm::sys::FileStatus;
  1995. llvm::sys::PathWithStatus CompleteFilePath(File);
  1996. llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
  1997. if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
  1998. if (const FileStatus *MainStatus = MainPath.getFileStatus())
  1999. if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
  2000. Line > 1)
  2001. OverrideMainBuffer
  2002. = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
  2003. Line - 1);
  2004. }
  2005. // If the main file has been overridden due to the use of a preamble,
  2006. // make that override happen and introduce the preamble.
  2007. PreprocessorOpts.DisableStatCache = true;
  2008. StoredDiagnostics.insert(StoredDiagnostics.end(),
  2009. stored_diag_begin(),
  2010. stored_diag_afterDriver_begin());
  2011. if (OverrideMainBuffer) {
  2012. PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
  2013. PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
  2014. PreprocessorOpts.PrecompiledPreambleBytes.second
  2015. = PreambleEndsAtStartOfLine;
  2016. PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
  2017. PreprocessorOpts.DisablePCHValidation = true;
  2018. OwnedBuffers.push_back(OverrideMainBuffer);
  2019. } else {
  2020. PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
  2021. PreprocessorOpts.PrecompiledPreambleBytes.second = false;
  2022. }
  2023. // Disable the preprocessing record
  2024. PreprocessorOpts.DetailedRecord = false;
  2025. llvm::OwningPtr<SyntaxOnlyAction> Act;
  2026. Act.reset(new SyntaxOnlyAction);
  2027. if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
  2028. Clang->getFrontendOpts().Inputs[0].first)) {
  2029. if (OverrideMainBuffer) {
  2030. std::string ModName = getPreambleFile(this);
  2031. TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
  2032. getSourceManager(), PreambleDiagnostics,
  2033. StoredDiagnostics);
  2034. }
  2035. Act->Execute();
  2036. Act->EndSourceFile();
  2037. }
  2038. }
  2039. CXSaveError ASTUnit::Save(StringRef File) {
  2040. if (getDiagnostics().hasUnrecoverableErrorOccurred())
  2041. return CXSaveError_TranslationErrors;
  2042. // Write to a temporary file and later rename it to the actual file, to avoid
  2043. // possible race conditions.
  2044. llvm::SmallString<128> TempPath;
  2045. TempPath = File;
  2046. TempPath += "-%%%%%%%%";
  2047. int fd;
  2048. if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
  2049. /*makeAbsolute=*/false))
  2050. return CXSaveError_Unknown;
  2051. // FIXME: Can we somehow regenerate the stat cache here, or do we need to
  2052. // unconditionally create a stat cache when we parse the file?
  2053. llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
  2054. serialize(Out);
  2055. Out.close();
  2056. if (Out.has_error())
  2057. return CXSaveError_Unknown;
  2058. if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
  2059. bool exists;
  2060. llvm::sys::fs::remove(TempPath.str(), exists);
  2061. return CXSaveError_Unknown;
  2062. }
  2063. return CXSaveError_None;
  2064. }
  2065. bool ASTUnit::serialize(raw_ostream &OS) {
  2066. if (getDiagnostics().hasErrorOccurred())
  2067. return true;
  2068. std::vector<unsigned char> Buffer;
  2069. llvm::BitstreamWriter Stream(Buffer);
  2070. ASTWriter Writer(Stream);
  2071. // FIXME: Handle modules
  2072. Writer.WriteAST(getSema(), 0, std::string(), 0, "");
  2073. // Write the generated bitstream to "Out".
  2074. if (!Buffer.empty())
  2075. OS.write((char *)&Buffer.front(), Buffer.size());
  2076. return false;
  2077. }
  2078. typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
  2079. static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
  2080. unsigned Raw = L.getRawEncoding();
  2081. const unsigned MacroBit = 1U << 31;
  2082. L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
  2083. ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
  2084. }
  2085. void ASTUnit::TranslateStoredDiagnostics(
  2086. ASTReader *MMan,
  2087. StringRef ModName,
  2088. SourceManager &SrcMgr,
  2089. const SmallVectorImpl<StoredDiagnostic> &Diags,
  2090. SmallVectorImpl<StoredDiagnostic> &Out) {
  2091. // The stored diagnostic has the old source manager in it; update
  2092. // the locations to refer into the new source manager. We also need to remap
  2093. // all the locations to the new view. This includes the diag location, any
  2094. // associated source ranges, and the source ranges of associated fix-its.
  2095. // FIXME: There should be a cleaner way to do this.
  2096. SmallVector<StoredDiagnostic, 4> Result;
  2097. Result.reserve(Diags.size());
  2098. assert(MMan && "Don't have a module manager");
  2099. serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
  2100. assert(Mod && "Don't have preamble module");
  2101. SLocRemap &Remap = Mod->SLocRemap;
  2102. for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
  2103. // Rebuild the StoredDiagnostic.
  2104. const StoredDiagnostic &SD = Diags[I];
  2105. SourceLocation L = SD.getLocation();
  2106. TranslateSLoc(L, Remap);
  2107. FullSourceLoc Loc(L, SrcMgr);
  2108. SmallVector<CharSourceRange, 4> Ranges;
  2109. Ranges.reserve(SD.range_size());
  2110. for (StoredDiagnostic::range_iterator I = SD.range_begin(),
  2111. E = SD.range_end();
  2112. I != E; ++I) {
  2113. SourceLocation BL = I->getBegin();
  2114. TranslateSLoc(BL, Remap);
  2115. SourceLocation EL = I->getEnd();
  2116. TranslateSLoc(EL, Remap);
  2117. Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
  2118. }
  2119. SmallVector<FixItHint, 2> FixIts;
  2120. FixIts.reserve(SD.fixit_size());
  2121. for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
  2122. E = SD.fixit_end();
  2123. I != E; ++I) {
  2124. FixIts.push_back(FixItHint());
  2125. FixItHint &FH = FixIts.back();
  2126. FH.CodeToInsert = I->CodeToInsert;
  2127. SourceLocation BL = I->RemoveRange.getBegin();
  2128. TranslateSLoc(BL, Remap);
  2129. SourceLocation EL = I->RemoveRange.getEnd();
  2130. TranslateSLoc(EL, Remap);
  2131. FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
  2132. I->RemoveRange.isTokenRange());
  2133. }
  2134. Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
  2135. SD.getMessage(), Loc, Ranges, FixIts));
  2136. }
  2137. Result.swap(Out);
  2138. }
  2139. static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
  2140. std::pair<unsigned, Decl *> R) {
  2141. return L.first < R.first;
  2142. }
  2143. void ASTUnit::addFileLevelDecl(Decl *D) {
  2144. assert(D);
  2145. // We only care about local declarations.
  2146. if (D->isFromASTFile())
  2147. return;
  2148. SourceManager &SM = *SourceMgr;
  2149. SourceLocation Loc = D->getLocation();
  2150. if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
  2151. return;
  2152. // We only keep track of the file-level declarations of each file.
  2153. if (!D->getLexicalDeclContext()->isFileContext())
  2154. return;
  2155. SourceLocation FileLoc = SM.getFileLoc(Loc);
  2156. assert(SM.isLocalSourceLocation(FileLoc));
  2157. FileID FID;
  2158. unsigned Offset;
  2159. llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
  2160. if (FID.isInvalid())
  2161. return;
  2162. LocDeclsTy *&Decls = FileDecls[FID];
  2163. if (!Decls)
  2164. Decls = new LocDeclsTy();
  2165. std::pair<unsigned, Decl *> LocDecl(Offset, D);
  2166. if (Decls->empty() || Decls->back().first <= Offset) {
  2167. Decls->push_back(LocDecl);
  2168. return;
  2169. }
  2170. LocDeclsTy::iterator
  2171. I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
  2172. Decls->insert(I, LocDecl);
  2173. }
  2174. void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
  2175. SmallVectorImpl<Decl *> &Decls) {
  2176. if (File.isInvalid())
  2177. return;
  2178. if (SourceMgr->isLoadedFileID(File)) {
  2179. assert(Ctx->getExternalSource() && "No external source!");
  2180. return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
  2181. Decls);
  2182. }
  2183. FileDeclsTy::iterator I = FileDecls.find(File);
  2184. if (I == FileDecls.end())
  2185. return;
  2186. LocDeclsTy &LocDecls = *I->second;
  2187. if (LocDecls.empty())
  2188. return;
  2189. LocDeclsTy::iterator
  2190. BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
  2191. std::make_pair(Offset, (Decl*)0), compLocDecl);
  2192. if (BeginIt != LocDecls.begin())
  2193. --BeginIt;
  2194. // If we are pointing at a top-level decl inside an objc container, we need
  2195. // to backtrack until we find it otherwise we will fail to report that the
  2196. // region overlaps with an objc container.
  2197. while (BeginIt != LocDecls.begin() &&
  2198. BeginIt->second->isTopLevelDeclInObjCContainer())
  2199. --BeginIt;
  2200. LocDeclsTy::iterator
  2201. EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
  2202. std::make_pair(Offset+Length, (Decl*)0),
  2203. compLocDecl);
  2204. if (EndIt != LocDecls.end())
  2205. ++EndIt;
  2206. for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
  2207. Decls.push_back(DIt->second);
  2208. }
  2209. SourceLocation ASTUnit::getLocation(const FileEntry *File,
  2210. unsigned Line, unsigned Col) const {
  2211. const SourceManager &SM = getSourceManager();
  2212. SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
  2213. return SM.getMacroArgExpandedLocation(Loc);
  2214. }
  2215. SourceLocation ASTUnit::getLocation(const FileEntry *File,
  2216. unsigned Offset) const {
  2217. const SourceManager &SM = getSourceManager();
  2218. SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
  2219. return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
  2220. }
  2221. /// \brief If \arg Loc is a loaded location from the preamble, returns
  2222. /// the corresponding local location of the main file, otherwise it returns
  2223. /// \arg Loc.
  2224. SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
  2225. FileID PreambleID;
  2226. if (SourceMgr)
  2227. PreambleID = SourceMgr->getPreambleFileID();
  2228. if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
  2229. return Loc;
  2230. unsigned Offs;
  2231. if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
  2232. SourceLocation FileLoc
  2233. = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
  2234. return FileLoc.getLocWithOffset(Offs);
  2235. }
  2236. return Loc;
  2237. }
  2238. /// \brief If \arg Loc is a local location of the main file but inside the
  2239. /// preamble chunk, returns the corresponding loaded location from the
  2240. /// preamble, otherwise it returns \arg Loc.
  2241. SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
  2242. FileID PreambleID;
  2243. if (SourceMgr)
  2244. PreambleID = SourceMgr->getPreambleFileID();
  2245. if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
  2246. return Loc;
  2247. unsigned Offs;
  2248. if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
  2249. Offs < Preamble.size()) {
  2250. SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
  2251. return FileLoc.getLocWithOffset(Offs);
  2252. }
  2253. return Loc;
  2254. }
  2255. bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
  2256. FileID FID;
  2257. if (SourceMgr)
  2258. FID = SourceMgr->getPreambleFileID();
  2259. if (Loc.isInvalid() || FID.isInvalid())
  2260. return false;
  2261. return SourceMgr->isInFileID(Loc, FID);
  2262. }
  2263. bool ASTUnit::isInMainFileID(SourceLocation Loc) {
  2264. FileID FID;
  2265. if (SourceMgr)
  2266. FID = SourceMgr->getMainFileID();
  2267. if (Loc.isInvalid() || FID.isInvalid())
  2268. return false;
  2269. return SourceMgr->isInFileID(Loc, FID);
  2270. }
  2271. SourceLocation ASTUnit::getEndOfPreambleFileID() {
  2272. FileID FID;
  2273. if (SourceMgr)
  2274. FID = SourceMgr->getPreambleFileID();
  2275. if (FID.isInvalid())
  2276. return SourceLocation();
  2277. return SourceMgr->getLocForEndOfFile(FID);
  2278. }
  2279. SourceLocation ASTUnit::getStartOfMainFileID() {
  2280. FileID FID;
  2281. if (SourceMgr)
  2282. FID = SourceMgr->getMainFileID();
  2283. if (FID.isInvalid())
  2284. return SourceLocation();
  2285. return SourceMgr->getLocForStartOfFile(FID);
  2286. }
  2287. void ASTUnit::PreambleData::countLines() const {
  2288. NumLines = 0;
  2289. if (empty())
  2290. return;
  2291. for (std::vector<char>::const_iterator
  2292. I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
  2293. if (*I == '\n')
  2294. ++NumLines;
  2295. }
  2296. if (Buffer.back() != '\n')
  2297. ++NumLines;
  2298. }
  2299. #ifndef NDEBUG
  2300. ASTUnit::ConcurrencyState::ConcurrencyState() {
  2301. Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
  2302. }
  2303. ASTUnit::ConcurrencyState::~ConcurrencyState() {
  2304. delete static_cast<llvm::sys::MutexImpl *>(Mutex);
  2305. }
  2306. void ASTUnit::ConcurrencyState::start() {
  2307. bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
  2308. assert(acquired && "Concurrent access to ASTUnit!");
  2309. }
  2310. void ASTUnit::ConcurrencyState::finish() {
  2311. static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
  2312. }
  2313. #else // NDEBUG
  2314. ASTUnit::ConcurrencyState::ConcurrencyState() {}
  2315. ASTUnit::ConcurrencyState::~ConcurrencyState() {}
  2316. void ASTUnit::ConcurrencyState::start() {}
  2317. void ASTUnit::ConcurrencyState::finish() {}
  2318. #endif