ASTUnit.cpp 105 KB

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