ASTUnit.cpp 95 KB

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