ASTUnit.cpp 101 KB

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