CGDebugInfo.cpp 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667
  1. //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
  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. // This coordinates the debug information generation while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "CGBlocks.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/DeclFriend.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/Basic/SourceManager.h"
  24. #include "clang/Basic/FileManager.h"
  25. #include "clang/Basic/Version.h"
  26. #include "clang/Frontend/CodeGenOptions.h"
  27. #include "llvm/Constants.h"
  28. #include "llvm/DerivedTypes.h"
  29. #include "llvm/Instructions.h"
  30. #include "llvm/Intrinsics.h"
  31. #include "llvm/Module.h"
  32. #include "llvm/ADT/StringExtras.h"
  33. #include "llvm/ADT/SmallVector.h"
  34. #include "llvm/Support/Dwarf.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "llvm/Target/TargetData.h"
  37. using namespace clang;
  38. using namespace clang::CodeGen;
  39. CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
  40. : CGM(CGM), DBuilder(CGM.getModule()),
  41. BlockLiteralGenericSet(false) {
  42. CreateCompileUnit();
  43. }
  44. CGDebugInfo::~CGDebugInfo() {
  45. assert(LexicalBlockStack.empty() &&
  46. "Region stack mismatch, stack not empty!");
  47. }
  48. void CGDebugInfo::setLocation(SourceLocation Loc) {
  49. // If the new location isn't valid return.
  50. if (!Loc.isValid()) return;
  51. CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
  52. // If we've changed files in the middle of a lexical scope go ahead
  53. // and create a new lexical scope with file node if it's different
  54. // from the one in the scope.
  55. if (LexicalBlockStack.empty()) return;
  56. SourceManager &SM = CGM.getContext().getSourceManager();
  57. PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
  58. PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
  59. if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
  60. !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
  61. return;
  62. llvm::MDNode *LB = LexicalBlockStack.back();
  63. llvm::DIScope Scope = llvm::DIScope(LB);
  64. if (Scope.isLexicalBlockFile()) {
  65. llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
  66. llvm::DIDescriptor D
  67. = DBuilder.createLexicalBlockFile(LBF.getScope(),
  68. getOrCreateFile(CurLoc));
  69. llvm::MDNode *N = D;
  70. LexicalBlockStack.pop_back();
  71. LexicalBlockStack.push_back(N);
  72. } else if (Scope.isLexicalBlock()) {
  73. llvm::DIDescriptor D
  74. = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
  75. llvm::MDNode *N = D;
  76. LexicalBlockStack.pop_back();
  77. LexicalBlockStack.push_back(N);
  78. }
  79. }
  80. /// getContextDescriptor - Get context info for the decl.
  81. llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
  82. if (!Context)
  83. return TheCU;
  84. llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
  85. I = RegionMap.find(Context);
  86. if (I != RegionMap.end())
  87. return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
  88. // Check namespace.
  89. if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
  90. return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
  91. if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
  92. if (!RDecl->isDependentType()) {
  93. llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
  94. getOrCreateMainFile());
  95. return llvm::DIDescriptor(Ty);
  96. }
  97. }
  98. return TheCU;
  99. }
  100. /// getFunctionName - Get function name for the given FunctionDecl. If the
  101. /// name is constructred on demand (e.g. C++ destructor) then the name
  102. /// is stored on the side.
  103. StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
  104. assert (FD && "Invalid FunctionDecl!");
  105. IdentifierInfo *FII = FD->getIdentifier();
  106. FunctionTemplateSpecializationInfo *Info
  107. = FD->getTemplateSpecializationInfo();
  108. if (!Info && FII)
  109. return FII->getName();
  110. // Otherwise construct human readable name for debug info.
  111. std::string NS = FD->getNameAsString();
  112. // Add any template specialization args.
  113. if (Info) {
  114. const TemplateArgumentList *TArgs = Info->TemplateArguments;
  115. const TemplateArgument *Args = TArgs->data();
  116. unsigned NumArgs = TArgs->size();
  117. PrintingPolicy Policy(CGM.getLangOpts());
  118. NS += TemplateSpecializationType::PrintTemplateArgumentList(Args,
  119. NumArgs,
  120. Policy);
  121. }
  122. // Copy this name on the side and use its reference.
  123. char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
  124. memcpy(StrPtr, NS.data(), NS.length());
  125. return StringRef(StrPtr, NS.length());
  126. }
  127. StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
  128. SmallString<256> MethodName;
  129. llvm::raw_svector_ostream OS(MethodName);
  130. OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
  131. const DeclContext *DC = OMD->getDeclContext();
  132. if (const ObjCImplementationDecl *OID =
  133. dyn_cast<const ObjCImplementationDecl>(DC)) {
  134. OS << OID->getName();
  135. } else if (const ObjCInterfaceDecl *OID =
  136. dyn_cast<const ObjCInterfaceDecl>(DC)) {
  137. OS << OID->getName();
  138. } else if (const ObjCCategoryImplDecl *OCD =
  139. dyn_cast<const ObjCCategoryImplDecl>(DC)){
  140. OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
  141. OCD->getIdentifier()->getNameStart() << ')';
  142. }
  143. OS << ' ' << OMD->getSelector().getAsString() << ']';
  144. char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
  145. memcpy(StrPtr, MethodName.begin(), OS.tell());
  146. return StringRef(StrPtr, OS.tell());
  147. }
  148. /// getSelectorName - Return selector name. This is used for debugging
  149. /// info.
  150. StringRef CGDebugInfo::getSelectorName(Selector S) {
  151. const std::string &SName = S.getAsString();
  152. char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
  153. memcpy(StrPtr, SName.data(), SName.size());
  154. return StringRef(StrPtr, SName.size());
  155. }
  156. /// getClassName - Get class name including template argument list.
  157. StringRef
  158. CGDebugInfo::getClassName(const RecordDecl *RD) {
  159. const ClassTemplateSpecializationDecl *Spec
  160. = dyn_cast<ClassTemplateSpecializationDecl>(RD);
  161. if (!Spec)
  162. return RD->getName();
  163. const TemplateArgument *Args;
  164. unsigned NumArgs;
  165. if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
  166. const TemplateSpecializationType *TST =
  167. cast<TemplateSpecializationType>(TAW->getType());
  168. Args = TST->getArgs();
  169. NumArgs = TST->getNumArgs();
  170. } else {
  171. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  172. Args = TemplateArgs.data();
  173. NumArgs = TemplateArgs.size();
  174. }
  175. StringRef Name = RD->getIdentifier()->getName();
  176. PrintingPolicy Policy(CGM.getLangOpts());
  177. std::string TemplateArgList =
  178. TemplateSpecializationType::PrintTemplateArgumentList(Args, NumArgs, Policy);
  179. // Copy this name on the side and use its reference.
  180. size_t Length = Name.size() + TemplateArgList.size();
  181. char *StrPtr = DebugInfoNames.Allocate<char>(Length);
  182. memcpy(StrPtr, Name.data(), Name.size());
  183. memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
  184. return StringRef(StrPtr, Length);
  185. }
  186. /// getOrCreateFile - Get the file debug info descriptor for the input location.
  187. llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
  188. if (!Loc.isValid())
  189. // If Location is not valid then use main input file.
  190. return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
  191. SourceManager &SM = CGM.getContext().getSourceManager();
  192. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  193. if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
  194. // If the location is not valid then use main input file.
  195. return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
  196. // Cache the results.
  197. const char *fname = PLoc.getFilename();
  198. llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
  199. DIFileCache.find(fname);
  200. if (it != DIFileCache.end()) {
  201. // Verify that the information still exists.
  202. if (&*it->second)
  203. return llvm::DIFile(cast<llvm::MDNode>(it->second));
  204. }
  205. llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
  206. DIFileCache[fname] = F;
  207. return F;
  208. }
  209. /// getOrCreateMainFile - Get the file info for main compile unit.
  210. llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
  211. return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
  212. }
  213. /// getLineNumber - Get line number for the location. If location is invalid
  214. /// then use current location.
  215. unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
  216. if (Loc.isInvalid() && CurLoc.isInvalid())
  217. return 0;
  218. SourceManager &SM = CGM.getContext().getSourceManager();
  219. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  220. return PLoc.isValid()? PLoc.getLine() : 0;
  221. }
  222. /// getColumnNumber - Get column number for the location. If location is
  223. /// invalid then use current location.
  224. unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
  225. if (Loc.isInvalid() && CurLoc.isInvalid())
  226. return 0;
  227. SourceManager &SM = CGM.getContext().getSourceManager();
  228. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  229. return PLoc.isValid()? PLoc.getColumn() : 0;
  230. }
  231. StringRef CGDebugInfo::getCurrentDirname() {
  232. if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
  233. return CGM.getCodeGenOpts().DebugCompilationDir;
  234. if (!CWDName.empty())
  235. return CWDName;
  236. SmallString<256> CWD;
  237. llvm::sys::fs::current_path(CWD);
  238. char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
  239. memcpy(CompDirnamePtr, CWD.data(), CWD.size());
  240. return CWDName = StringRef(CompDirnamePtr, CWD.size());
  241. }
  242. /// CreateCompileUnit - Create new compile unit.
  243. void CGDebugInfo::CreateCompileUnit() {
  244. // Get absolute path name.
  245. SourceManager &SM = CGM.getContext().getSourceManager();
  246. std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
  247. if (MainFileName.empty())
  248. MainFileName = "<unknown>";
  249. // The main file name provided via the "-main-file-name" option contains just
  250. // the file name itself with no path information. This file name may have had
  251. // a relative path, so we look into the actual file entry for the main
  252. // file to determine the real absolute path for the file.
  253. std::string MainFileDir;
  254. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  255. MainFileDir = MainFile->getDir()->getName();
  256. if (MainFileDir != ".")
  257. MainFileName = MainFileDir + "/" + MainFileName;
  258. }
  259. // Save filename string.
  260. char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
  261. memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
  262. StringRef Filename(FilenamePtr, MainFileName.length());
  263. unsigned LangTag;
  264. const LangOptions &LO = CGM.getLangOpts();
  265. if (LO.CPlusPlus) {
  266. if (LO.ObjC1)
  267. LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
  268. else
  269. LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
  270. } else if (LO.ObjC1) {
  271. LangTag = llvm::dwarf::DW_LANG_ObjC;
  272. } else if (LO.C99) {
  273. LangTag = llvm::dwarf::DW_LANG_C99;
  274. } else {
  275. LangTag = llvm::dwarf::DW_LANG_C89;
  276. }
  277. std::string Producer = getClangFullVersion();
  278. // Figure out which version of the ObjC runtime we have.
  279. unsigned RuntimeVers = 0;
  280. if (LO.ObjC1)
  281. RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
  282. // Create new compile unit.
  283. DBuilder.createCompileUnit(
  284. LangTag, Filename, getCurrentDirname(),
  285. Producer,
  286. LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
  287. // FIXME - Eliminate TheCU.
  288. TheCU = llvm::DICompileUnit(DBuilder.getCU());
  289. }
  290. /// CreateType - Get the Basic type from the cache or create a new
  291. /// one if necessary.
  292. llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
  293. unsigned Encoding = 0;
  294. const char *BTName = NULL;
  295. switch (BT->getKind()) {
  296. #define BUILTIN_TYPE(Id, SingletonId)
  297. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  298. case BuiltinType::Id:
  299. #include "clang/AST/BuiltinTypes.def"
  300. case BuiltinType::Dependent:
  301. llvm_unreachable("Unexpected builtin type");
  302. case BuiltinType::NullPtr:
  303. return DBuilder.
  304. createNullPtrType(BT->getName(CGM.getContext().getLangOpts()));
  305. case BuiltinType::Void:
  306. return llvm::DIType();
  307. case BuiltinType::ObjCClass:
  308. return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  309. "objc_class", TheCU,
  310. getOrCreateMainFile(), 0);
  311. case BuiltinType::ObjCId: {
  312. // typedef struct objc_class *Class;
  313. // typedef struct objc_object {
  314. // Class isa;
  315. // } *id;
  316. // TODO: Cache these two types to avoid duplicates.
  317. llvm::DIType OCTy =
  318. DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  319. "objc_class", TheCU, getOrCreateMainFile(), 0);
  320. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  321. llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
  322. SmallVector<llvm::Value *, 16> EltTys;
  323. llvm::DIType FieldTy =
  324. DBuilder.createMemberType(getOrCreateMainFile(), "isa",
  325. getOrCreateMainFile(), 0, Size,
  326. 0, 0, 0, ISATy);
  327. EltTys.push_back(FieldTy);
  328. llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
  329. return DBuilder.createStructType(TheCU, "objc_object",
  330. getOrCreateMainFile(),
  331. 0, 0, 0, 0, Elements);
  332. }
  333. case BuiltinType::ObjCSel: {
  334. return
  335. DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  336. "objc_selector", TheCU, getOrCreateMainFile(),
  337. 0);
  338. }
  339. case BuiltinType::UChar:
  340. case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
  341. case BuiltinType::Char_S:
  342. case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
  343. case BuiltinType::Char16:
  344. case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
  345. case BuiltinType::UShort:
  346. case BuiltinType::UInt:
  347. case BuiltinType::UInt128:
  348. case BuiltinType::ULong:
  349. case BuiltinType::WChar_U:
  350. case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
  351. case BuiltinType::Short:
  352. case BuiltinType::Int:
  353. case BuiltinType::Int128:
  354. case BuiltinType::Long:
  355. case BuiltinType::WChar_S:
  356. case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
  357. case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
  358. case BuiltinType::Half:
  359. case BuiltinType::Float:
  360. case BuiltinType::LongDouble:
  361. case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
  362. }
  363. switch (BT->getKind()) {
  364. case BuiltinType::Long: BTName = "long int"; break;
  365. case BuiltinType::LongLong: BTName = "long long int"; break;
  366. case BuiltinType::ULong: BTName = "long unsigned int"; break;
  367. case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
  368. default:
  369. BTName = BT->getName(CGM.getContext().getLangOpts());
  370. break;
  371. }
  372. // Bit size, align and offset of the type.
  373. uint64_t Size = CGM.getContext().getTypeSize(BT);
  374. uint64_t Align = CGM.getContext().getTypeAlign(BT);
  375. llvm::DIType DbgTy =
  376. DBuilder.createBasicType(BTName, Size, Align, Encoding);
  377. return DbgTy;
  378. }
  379. llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
  380. // Bit size, align and offset of the type.
  381. unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
  382. if (Ty->isComplexIntegerType())
  383. Encoding = llvm::dwarf::DW_ATE_lo_user;
  384. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  385. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  386. llvm::DIType DbgTy =
  387. DBuilder.createBasicType("complex", Size, Align, Encoding);
  388. return DbgTy;
  389. }
  390. /// CreateCVRType - Get the qualified type from the cache or create
  391. /// a new one if necessary.
  392. llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
  393. QualifierCollector Qc;
  394. const Type *T = Qc.strip(Ty);
  395. // Ignore these qualifiers for now.
  396. Qc.removeObjCGCAttr();
  397. Qc.removeAddressSpace();
  398. Qc.removeObjCLifetime();
  399. // We will create one Derived type for one qualifier and recurse to handle any
  400. // additional ones.
  401. unsigned Tag;
  402. if (Qc.hasConst()) {
  403. Tag = llvm::dwarf::DW_TAG_const_type;
  404. Qc.removeConst();
  405. } else if (Qc.hasVolatile()) {
  406. Tag = llvm::dwarf::DW_TAG_volatile_type;
  407. Qc.removeVolatile();
  408. } else if (Qc.hasRestrict()) {
  409. Tag = llvm::dwarf::DW_TAG_restrict_type;
  410. Qc.removeRestrict();
  411. } else {
  412. assert(Qc.empty() && "Unknown type qualifier for debug info");
  413. return getOrCreateType(QualType(T, 0), Unit);
  414. }
  415. llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
  416. // No need to fill in the Name, Line, Size, Alignment, Offset in case of
  417. // CVR derived types.
  418. llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
  419. return DbgTy;
  420. }
  421. llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
  422. llvm::DIFile Unit) {
  423. llvm::DIType DbgTy =
  424. CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  425. Ty->getPointeeType(), Unit);
  426. return DbgTy;
  427. }
  428. llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
  429. llvm::DIFile Unit) {
  430. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  431. Ty->getPointeeType(), Unit);
  432. }
  433. // Creates a forward declaration for a RecordDecl in the given context.
  434. llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
  435. llvm::DIDescriptor Ctx) {
  436. llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
  437. unsigned Line = getLineNumber(RD->getLocation());
  438. StringRef RDName = RD->getName();
  439. // Get the tag.
  440. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  441. unsigned Tag = 0;
  442. if (CXXDecl) {
  443. RDName = getClassName(RD);
  444. Tag = llvm::dwarf::DW_TAG_class_type;
  445. }
  446. else if (RD->isStruct())
  447. Tag = llvm::dwarf::DW_TAG_structure_type;
  448. else if (RD->isUnion())
  449. Tag = llvm::dwarf::DW_TAG_union_type;
  450. else
  451. llvm_unreachable("Unknown RecordDecl type!");
  452. // Create the type.
  453. return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
  454. }
  455. // Walk up the context chain and create forward decls for record decls,
  456. // and normal descriptors for namespaces.
  457. llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
  458. if (!Context)
  459. return TheCU;
  460. // See if we already have the parent.
  461. llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
  462. I = RegionMap.find(Context);
  463. if (I != RegionMap.end())
  464. return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
  465. // Check namespace.
  466. if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
  467. return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
  468. if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
  469. if (!RD->isDependentType()) {
  470. llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
  471. getOrCreateMainFile());
  472. return llvm::DIDescriptor(Ty);
  473. }
  474. }
  475. return TheCU;
  476. }
  477. /// CreatePointeeType - Create Pointee type. If Pointee is a record
  478. /// then emit record's fwd if debug info size reduction is enabled.
  479. llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
  480. llvm::DIFile Unit) {
  481. if (CGM.getCodeGenOpts().DebugInfo != CodeGenOptions::LimitedDebugInfo)
  482. return getOrCreateType(PointeeTy, Unit);
  483. // Limit debug info for the pointee type.
  484. // If we have an existing type, use that, it's still smaller than creating
  485. // a new type.
  486. llvm::DIType Ty = getTypeOrNull(PointeeTy);
  487. if (Ty.Verify()) return Ty;
  488. // Handle qualifiers.
  489. if (PointeeTy.hasLocalQualifiers())
  490. return CreateQualifiedType(PointeeTy, Unit);
  491. if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
  492. RecordDecl *RD = RTy->getDecl();
  493. llvm::DIDescriptor FDContext =
  494. getContextDescriptor(cast<Decl>(RD->getDeclContext()));
  495. llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
  496. TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
  497. return RetTy;
  498. }
  499. return getOrCreateType(PointeeTy, Unit);
  500. }
  501. llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
  502. const Type *Ty,
  503. QualType PointeeTy,
  504. llvm::DIFile Unit) {
  505. if (Tag == llvm::dwarf::DW_TAG_reference_type)
  506. return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
  507. // Bit size, align and offset of the type.
  508. // Size is always the size of a pointer. We can't use getTypeSize here
  509. // because that does not return the correct value for references.
  510. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  511. uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
  512. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  513. return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
  514. Size, Align);
  515. }
  516. llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
  517. llvm::DIFile Unit) {
  518. if (BlockLiteralGenericSet)
  519. return BlockLiteralGeneric;
  520. SmallVector<llvm::Value *, 8> EltTys;
  521. llvm::DIType FieldTy;
  522. QualType FType;
  523. uint64_t FieldSize, FieldOffset;
  524. unsigned FieldAlign;
  525. llvm::DIArray Elements;
  526. llvm::DIType EltTy, DescTy;
  527. FieldOffset = 0;
  528. FType = CGM.getContext().UnsignedLongTy;
  529. EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
  530. EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
  531. Elements = DBuilder.getOrCreateArray(EltTys);
  532. EltTys.clear();
  533. unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
  534. unsigned LineNo = getLineNumber(CurLoc);
  535. EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
  536. Unit, LineNo, FieldOffset, 0,
  537. Flags, Elements);
  538. // Bit size, align and offset of the type.
  539. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  540. DescTy = DBuilder.createPointerType(EltTy, Size);
  541. FieldOffset = 0;
  542. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  543. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  544. FType = CGM.getContext().IntTy;
  545. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  546. EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
  547. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  548. EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
  549. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  550. FieldTy = DescTy;
  551. FieldSize = CGM.getContext().getTypeSize(Ty);
  552. FieldAlign = CGM.getContext().getTypeAlign(Ty);
  553. FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
  554. LineNo, FieldSize, FieldAlign,
  555. FieldOffset, 0, FieldTy);
  556. EltTys.push_back(FieldTy);
  557. FieldOffset += FieldSize;
  558. Elements = DBuilder.getOrCreateArray(EltTys);
  559. EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
  560. Unit, LineNo, FieldOffset, 0,
  561. Flags, Elements);
  562. BlockLiteralGenericSet = true;
  563. BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
  564. return BlockLiteralGeneric;
  565. }
  566. llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
  567. // Typedefs are derived from some other type. If we have a typedef of a
  568. // typedef, make sure to emit the whole chain.
  569. llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
  570. if (!Src.Verify())
  571. return llvm::DIType();
  572. // We don't set size information, but do specify where the typedef was
  573. // declared.
  574. unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
  575. const TypedefNameDecl *TyDecl = Ty->getDecl();
  576. llvm::DIDescriptor TypedefContext =
  577. getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
  578. return
  579. DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
  580. }
  581. llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
  582. llvm::DIFile Unit) {
  583. SmallVector<llvm::Value *, 16> EltTys;
  584. // Add the result type at least.
  585. EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
  586. // Set up remainder of arguments if there is a prototype.
  587. // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
  588. if (isa<FunctionNoProtoType>(Ty))
  589. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  590. else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
  591. for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
  592. EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
  593. }
  594. llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
  595. llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
  596. return DbgTy;
  597. }
  598. void CGDebugInfo::
  599. CollectRecordStaticVars(const RecordDecl *RD, llvm::DIType FwdDecl) {
  600. for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
  601. I != E; ++I)
  602. if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
  603. if (V->getInit()) {
  604. const APValue *Value = V->evaluateValue();
  605. if (Value && Value->isInt()) {
  606. llvm::ConstantInt *CI
  607. = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
  608. // Create the descriptor for static variable.
  609. llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
  610. StringRef VName = V->getName();
  611. llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
  612. // Do not use DIGlobalVariable for enums.
  613. if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
  614. DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
  615. getLineNumber(V->getLocation()),
  616. VTy, true, CI);
  617. }
  618. }
  619. }
  620. }
  621. }
  622. llvm::DIType CGDebugInfo::createFieldType(StringRef name,
  623. QualType type,
  624. uint64_t sizeInBitsOverride,
  625. SourceLocation loc,
  626. AccessSpecifier AS,
  627. uint64_t offsetInBits,
  628. llvm::DIFile tunit,
  629. llvm::DIDescriptor scope) {
  630. llvm::DIType debugType = getOrCreateType(type, tunit);
  631. // Get the location for the field.
  632. llvm::DIFile file = getOrCreateFile(loc);
  633. unsigned line = getLineNumber(loc);
  634. uint64_t sizeInBits = 0;
  635. unsigned alignInBits = 0;
  636. if (!type->isIncompleteArrayType()) {
  637. llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
  638. if (sizeInBitsOverride)
  639. sizeInBits = sizeInBitsOverride;
  640. }
  641. unsigned flags = 0;
  642. if (AS == clang::AS_private)
  643. flags |= llvm::DIDescriptor::FlagPrivate;
  644. else if (AS == clang::AS_protected)
  645. flags |= llvm::DIDescriptor::FlagProtected;
  646. return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
  647. alignInBits, offsetInBits, flags, debugType);
  648. }
  649. /// CollectRecordFields - A helper function to collect debug info for
  650. /// record fields. This is used while creating debug info entry for a Record.
  651. void CGDebugInfo::
  652. CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
  653. SmallVectorImpl<llvm::Value *> &elements,
  654. llvm::DIType RecordTy) {
  655. unsigned fieldNo = 0;
  656. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
  657. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
  658. // For C++11 Lambdas a Fields will be the same as a Capture, but the Capture
  659. // has the name and the location of the variable so we should iterate over
  660. // both concurrently.
  661. if (CXXDecl && CXXDecl->isLambda()) {
  662. RecordDecl::field_iterator Field = CXXDecl->field_begin();
  663. unsigned fieldno = 0;
  664. for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
  665. E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
  666. const LambdaExpr::Capture C = *I;
  667. // TODO: Need to handle 'this' in some way by probably renaming the
  668. // this of the lambda class and having a field member of 'this'.
  669. if (C.capturesVariable()) {
  670. VarDecl *V = C.getCapturedVar();
  671. llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
  672. StringRef VName = V->getName();
  673. uint64_t SizeInBitsOverride = 0;
  674. if (Field->isBitField()) {
  675. SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
  676. assert(SizeInBitsOverride && "found named 0-width bitfield");
  677. }
  678. llvm::DIType fieldType
  679. = createFieldType(VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
  680. Field->getAccess(), layout.getFieldOffset(fieldno),
  681. VUnit, RecordTy);
  682. elements.push_back(fieldType);
  683. }
  684. }
  685. } else {
  686. bool IsMsStruct = record->hasAttr<MsStructAttr>();
  687. const FieldDecl *LastFD = 0;
  688. for (RecordDecl::field_iterator I = record->field_begin(),
  689. E = record->field_end();
  690. I != E; ++I, ++fieldNo) {
  691. FieldDecl *field = &*I;
  692. if (IsMsStruct) {
  693. // Zero-length bitfields following non-bitfield members are ignored
  694. if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
  695. --fieldNo;
  696. continue;
  697. }
  698. LastFD = field;
  699. }
  700. StringRef name = field->getName();
  701. QualType type = field->getType();
  702. // Ignore unnamed fields unless they're anonymous structs/unions.
  703. if (name.empty() && !type->isRecordType()) {
  704. LastFD = field;
  705. continue;
  706. }
  707. uint64_t SizeInBitsOverride = 0;
  708. if (field->isBitField()) {
  709. SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
  710. assert(SizeInBitsOverride && "found named 0-width bitfield");
  711. }
  712. llvm::DIType fieldType
  713. = createFieldType(name, type, SizeInBitsOverride,
  714. field->getLocation(), field->getAccess(),
  715. layout.getFieldOffset(fieldNo), tunit, RecordTy);
  716. elements.push_back(fieldType);
  717. }
  718. }
  719. }
  720. /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
  721. /// function type is not updated to include implicit "this" pointer. Use this
  722. /// routine to get a method type which includes "this" pointer.
  723. llvm::DIType
  724. CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
  725. llvm::DIFile Unit) {
  726. llvm::DIType FnTy
  727. = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
  728. 0),
  729. Unit);
  730. // Add "this" pointer.
  731. llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
  732. assert (Args.getNumElements() && "Invalid number of arguments!");
  733. SmallVector<llvm::Value *, 16> Elts;
  734. // First element is always return type. For 'void' functions it is NULL.
  735. Elts.push_back(Args.getElement(0));
  736. if (!Method->isStatic()) {
  737. // "this" pointer is always first argument.
  738. QualType ThisPtr = Method->getThisType(CGM.getContext());
  739. const CXXRecordDecl *RD = Method->getParent();
  740. if (isa<ClassTemplateSpecializationDecl>(RD)) {
  741. // Create pointer type directly in this case.
  742. const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
  743. QualType PointeeTy = ThisPtrTy->getPointeeType();
  744. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  745. uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
  746. uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
  747. llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
  748. llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
  749. TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
  750. // TODO: This and the artificial type below are misleading, the
  751. // types aren't artificial the argument is, but the current
  752. // metadata doesn't represent that.
  753. ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
  754. Elts.push_back(ThisPtrType);
  755. } else {
  756. llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
  757. TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
  758. ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
  759. Elts.push_back(ThisPtrType);
  760. }
  761. }
  762. // Copy rest of the arguments.
  763. for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
  764. Elts.push_back(Args.getElement(i));
  765. llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
  766. return DBuilder.createSubroutineType(Unit, EltTypeArray);
  767. }
  768. /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
  769. /// inside a function.
  770. static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
  771. if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
  772. return isFunctionLocalClass(NRD);
  773. if (isa<FunctionDecl>(RD->getDeclContext()))
  774. return true;
  775. return false;
  776. }
  777. /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
  778. /// a single member function GlobalDecl.
  779. llvm::DISubprogram
  780. CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
  781. llvm::DIFile Unit,
  782. llvm::DIType RecordTy) {
  783. bool IsCtorOrDtor =
  784. isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
  785. StringRef MethodName = getFunctionName(Method);
  786. llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
  787. // Since a single ctor/dtor corresponds to multiple functions, it doesn't
  788. // make sense to give a single ctor/dtor a linkage name.
  789. StringRef MethodLinkageName;
  790. if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
  791. MethodLinkageName = CGM.getMangledName(Method);
  792. // Get the location for the method.
  793. llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
  794. unsigned MethodLine = getLineNumber(Method->getLocation());
  795. // Collect virtual method info.
  796. llvm::DIType ContainingType;
  797. unsigned Virtuality = 0;
  798. unsigned VIndex = 0;
  799. if (Method->isVirtual()) {
  800. if (Method->isPure())
  801. Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
  802. else
  803. Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
  804. // It doesn't make sense to give a virtual destructor a vtable index,
  805. // since a single destructor has two entries in the vtable.
  806. if (!isa<CXXDestructorDecl>(Method))
  807. VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
  808. ContainingType = RecordTy;
  809. }
  810. unsigned Flags = 0;
  811. if (Method->isImplicit())
  812. Flags |= llvm::DIDescriptor::FlagArtificial;
  813. AccessSpecifier Access = Method->getAccess();
  814. if (Access == clang::AS_private)
  815. Flags |= llvm::DIDescriptor::FlagPrivate;
  816. else if (Access == clang::AS_protected)
  817. Flags |= llvm::DIDescriptor::FlagProtected;
  818. if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
  819. if (CXXC->isExplicit())
  820. Flags |= llvm::DIDescriptor::FlagExplicit;
  821. } else if (const CXXConversionDecl *CXXC =
  822. dyn_cast<CXXConversionDecl>(Method)) {
  823. if (CXXC->isExplicit())
  824. Flags |= llvm::DIDescriptor::FlagExplicit;
  825. }
  826. if (Method->hasPrototype())
  827. Flags |= llvm::DIDescriptor::FlagPrototyped;
  828. llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
  829. llvm::DISubprogram SP =
  830. DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
  831. MethodDefUnit, MethodLine,
  832. MethodTy, /*isLocalToUnit=*/false,
  833. /* isDefinition=*/ false,
  834. Virtuality, VIndex, ContainingType,
  835. Flags, CGM.getLangOpts().Optimize, NULL,
  836. TParamsArray);
  837. SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
  838. return SP;
  839. }
  840. /// CollectCXXMemberFunctions - A helper function to collect debug info for
  841. /// C++ member functions. This is used while creating debug info entry for
  842. /// a Record.
  843. void CGDebugInfo::
  844. CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
  845. SmallVectorImpl<llvm::Value *> &EltTys,
  846. llvm::DIType RecordTy) {
  847. // Since we want more than just the individual member decls if we
  848. // have templated functions iterate over every declaration to gather
  849. // the functions.
  850. for(DeclContext::decl_iterator I = RD->decls_begin(),
  851. E = RD->decls_end(); I != E; ++I) {
  852. Decl *D = *I;
  853. if (D->isImplicit() && !D->isUsed())
  854. continue;
  855. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  856. EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
  857. else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
  858. for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
  859. SE = FTD->spec_end(); SI != SE; ++SI) {
  860. FunctionDecl *FD = *SI;
  861. if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(FD))
  862. EltTys.push_back(CreateCXXMemberFunction(M, Unit, RecordTy));
  863. }
  864. }
  865. }
  866. /// CollectCXXFriends - A helper function to collect debug info for
  867. /// C++ base classes. This is used while creating debug info entry for
  868. /// a Record.
  869. void CGDebugInfo::
  870. CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
  871. SmallVectorImpl<llvm::Value *> &EltTys,
  872. llvm::DIType RecordTy) {
  873. for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
  874. BE = RD->friend_end(); BI != BE; ++BI) {
  875. if ((*BI)->isUnsupportedFriend())
  876. continue;
  877. if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
  878. EltTys.push_back(DBuilder.createFriend(RecordTy,
  879. getOrCreateType(TInfo->getType(),
  880. Unit)));
  881. }
  882. }
  883. /// CollectCXXBases - A helper function to collect debug info for
  884. /// C++ base classes. This is used while creating debug info entry for
  885. /// a Record.
  886. void CGDebugInfo::
  887. CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
  888. SmallVectorImpl<llvm::Value *> &EltTys,
  889. llvm::DIType RecordTy) {
  890. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  891. for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
  892. BE = RD->bases_end(); BI != BE; ++BI) {
  893. unsigned BFlags = 0;
  894. uint64_t BaseOffset;
  895. const CXXRecordDecl *Base =
  896. cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
  897. if (BI->isVirtual()) {
  898. // virtual base offset offset is -ve. The code generator emits dwarf
  899. // expression where it expects +ve number.
  900. BaseOffset =
  901. 0 - CGM.getVTableContext()
  902. .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
  903. BFlags = llvm::DIDescriptor::FlagVirtual;
  904. } else
  905. BaseOffset = RL.getBaseClassOffsetInBits(Base);
  906. // FIXME: Inconsistent units for BaseOffset. It is in bytes when
  907. // BI->isVirtual() and bits when not.
  908. AccessSpecifier Access = BI->getAccessSpecifier();
  909. if (Access == clang::AS_private)
  910. BFlags |= llvm::DIDescriptor::FlagPrivate;
  911. else if (Access == clang::AS_protected)
  912. BFlags |= llvm::DIDescriptor::FlagProtected;
  913. llvm::DIType DTy =
  914. DBuilder.createInheritance(RecordTy,
  915. getOrCreateType(BI->getType(), Unit),
  916. BaseOffset, BFlags);
  917. EltTys.push_back(DTy);
  918. }
  919. }
  920. /// CollectTemplateParams - A helper function to collect template parameters.
  921. llvm::DIArray CGDebugInfo::
  922. CollectTemplateParams(const TemplateParameterList *TPList,
  923. const TemplateArgumentList &TAList,
  924. llvm::DIFile Unit) {
  925. SmallVector<llvm::Value *, 16> TemplateParams;
  926. for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
  927. const TemplateArgument &TA = TAList[i];
  928. const NamedDecl *ND = TPList->getParam(i);
  929. if (TA.getKind() == TemplateArgument::Type) {
  930. llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
  931. llvm::DITemplateTypeParameter TTP =
  932. DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
  933. TemplateParams.push_back(TTP);
  934. } else if (TA.getKind() == TemplateArgument::Integral) {
  935. llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
  936. llvm::DITemplateValueParameter TVP =
  937. DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
  938. TA.getAsIntegral()->getZExtValue());
  939. TemplateParams.push_back(TVP);
  940. }
  941. }
  942. return DBuilder.getOrCreateArray(TemplateParams);
  943. }
  944. /// CollectFunctionTemplateParams - A helper function to collect debug
  945. /// info for function template parameters.
  946. llvm::DIArray CGDebugInfo::
  947. CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
  948. if (FD->getTemplatedKind() ==
  949. FunctionDecl::TK_FunctionTemplateSpecialization) {
  950. const TemplateParameterList *TList =
  951. FD->getTemplateSpecializationInfo()->getTemplate()
  952. ->getTemplateParameters();
  953. return
  954. CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
  955. }
  956. return llvm::DIArray();
  957. }
  958. /// CollectCXXTemplateParams - A helper function to collect debug info for
  959. /// template parameters.
  960. llvm::DIArray CGDebugInfo::
  961. CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
  962. llvm::DIFile Unit) {
  963. llvm::PointerUnion<ClassTemplateDecl *,
  964. ClassTemplatePartialSpecializationDecl *>
  965. PU = TSpecial->getSpecializedTemplateOrPartial();
  966. TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
  967. PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
  968. PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
  969. const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
  970. return CollectTemplateParams(TPList, TAList, Unit);
  971. }
  972. /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
  973. llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
  974. if (VTablePtrType.isValid())
  975. return VTablePtrType;
  976. ASTContext &Context = CGM.getContext();
  977. /* Function type */
  978. llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
  979. llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
  980. llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
  981. unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
  982. llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
  983. "__vtbl_ptr_type");
  984. VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
  985. return VTablePtrType;
  986. }
  987. /// getVTableName - Get vtable name for the given Class.
  988. StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
  989. // Construct gdb compatible name name.
  990. std::string Name = "_vptr$" + RD->getNameAsString();
  991. // Copy this name on the side and use its reference.
  992. char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
  993. memcpy(StrPtr, Name.data(), Name.length());
  994. return StringRef(StrPtr, Name.length());
  995. }
  996. /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
  997. /// debug info entry in EltTys vector.
  998. void CGDebugInfo::
  999. CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
  1000. SmallVectorImpl<llvm::Value *> &EltTys) {
  1001. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1002. // If there is a primary base then it will hold vtable info.
  1003. if (RL.getPrimaryBase())
  1004. return;
  1005. // If this class is not dynamic then there is not any vtable info to collect.
  1006. if (!RD->isDynamicClass())
  1007. return;
  1008. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  1009. llvm::DIType VPTR
  1010. = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
  1011. 0, Size, 0, 0, 0,
  1012. getOrCreateVTablePtrType(Unit));
  1013. EltTys.push_back(VPTR);
  1014. }
  1015. /// getOrCreateRecordType - Emit record type's standalone debug info.
  1016. llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
  1017. SourceLocation Loc) {
  1018. llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
  1019. return T;
  1020. }
  1021. /// getOrCreateInterfaceType - Emit an objective c interface type standalone
  1022. /// debug info.
  1023. llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
  1024. SourceLocation Loc) {
  1025. llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
  1026. DBuilder.retainType(T);
  1027. return T;
  1028. }
  1029. /// CreateType - get structure or union type.
  1030. llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
  1031. RecordDecl *RD = Ty->getDecl();
  1032. // Get overall information about the record type for the debug info.
  1033. llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
  1034. // Records and classes and unions can all be recursive. To handle them, we
  1035. // first generate a debug descriptor for the struct as a forward declaration.
  1036. // Then (if it is a definition) we go through and get debug info for all of
  1037. // its members. Finally, we create a descriptor for the complete type (which
  1038. // may refer to the forward decl if the struct is recursive) and replace all
  1039. // uses of the forward declaration with the final definition.
  1040. llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
  1041. if (FwdDecl.isForwardDecl())
  1042. return FwdDecl;
  1043. llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
  1044. // Push the struct on region stack.
  1045. LexicalBlockStack.push_back(FwdDeclNode);
  1046. RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
  1047. // Add this to the completed types cache since we're completing it.
  1048. CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
  1049. // Convert all the elements.
  1050. SmallVector<llvm::Value *, 16> EltTys;
  1051. // Note: The split of CXXDecl information here is intentional, the
  1052. // gdb tests will depend on a certain ordering at printout. The debug
  1053. // information offsets are still correct if we merge them all together
  1054. // though.
  1055. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1056. if (CXXDecl) {
  1057. CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
  1058. CollectVTableInfo(CXXDecl, DefUnit, EltTys);
  1059. }
  1060. // Collect static variables with initializers and other fields.
  1061. CollectRecordStaticVars(RD, FwdDecl);
  1062. CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
  1063. llvm::DIArray TParamsArray;
  1064. if (CXXDecl) {
  1065. CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
  1066. CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
  1067. if (const ClassTemplateSpecializationDecl *TSpecial
  1068. = dyn_cast<ClassTemplateSpecializationDecl>(RD))
  1069. TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
  1070. }
  1071. LexicalBlockStack.pop_back();
  1072. RegionMap.erase(Ty->getDecl());
  1073. llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
  1074. // FIXME: Magic numbers ahoy! These should be changed when we
  1075. // get some enums in llvm/Analysis/DebugInfo.h to refer to
  1076. // them.
  1077. if (RD->isUnion())
  1078. FwdDeclNode->replaceOperandWith(10, Elements);
  1079. else if (CXXDecl) {
  1080. FwdDeclNode->replaceOperandWith(10, Elements);
  1081. FwdDeclNode->replaceOperandWith(13, TParamsArray);
  1082. } else
  1083. FwdDeclNode->replaceOperandWith(10, Elements);
  1084. RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
  1085. return llvm::DIType(FwdDeclNode);
  1086. }
  1087. /// CreateType - get objective-c object type.
  1088. llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
  1089. llvm::DIFile Unit) {
  1090. // Ignore protocols.
  1091. return getOrCreateType(Ty->getBaseType(), Unit);
  1092. }
  1093. /// CreateType - get objective-c interface type.
  1094. llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
  1095. llvm::DIFile Unit) {
  1096. ObjCInterfaceDecl *ID = Ty->getDecl();
  1097. if (!ID)
  1098. return llvm::DIType();
  1099. // Get overall information about the record type for the debug info.
  1100. llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
  1101. unsigned Line = getLineNumber(ID->getLocation());
  1102. unsigned RuntimeLang = TheCU.getLanguage();
  1103. // If this is just a forward declaration return a special forward-declaration
  1104. // debug type since we won't be able to lay out the entire type.
  1105. ObjCInterfaceDecl *Def = ID->getDefinition();
  1106. if (!Def) {
  1107. llvm::DIType FwdDecl =
  1108. DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  1109. ID->getName(), TheCU, DefUnit, Line,
  1110. RuntimeLang);
  1111. return FwdDecl;
  1112. }
  1113. ID = Def;
  1114. // Bit size, align and offset of the type.
  1115. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1116. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1117. unsigned Flags = 0;
  1118. if (ID->getImplementation())
  1119. Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
  1120. llvm::DIType RealDecl =
  1121. DBuilder.createStructType(Unit, ID->getName(), DefUnit,
  1122. Line, Size, Align, Flags,
  1123. llvm::DIArray(), RuntimeLang);
  1124. // Otherwise, insert it into the CompletedTypeCache so that recursive uses
  1125. // will find it and we're emitting the complete type.
  1126. CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
  1127. // Push the struct on region stack.
  1128. llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
  1129. LexicalBlockStack.push_back(FwdDeclNode);
  1130. RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
  1131. // Convert all the elements.
  1132. SmallVector<llvm::Value *, 16> EltTys;
  1133. ObjCInterfaceDecl *SClass = ID->getSuperClass();
  1134. if (SClass) {
  1135. llvm::DIType SClassTy =
  1136. getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
  1137. if (!SClassTy.isValid())
  1138. return llvm::DIType();
  1139. llvm::DIType InhTag =
  1140. DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
  1141. EltTys.push_back(InhTag);
  1142. }
  1143. for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
  1144. E = ID->prop_end(); I != E; ++I) {
  1145. const ObjCPropertyDecl *PD = &*I;
  1146. SourceLocation Loc = PD->getLocation();
  1147. llvm::DIFile PUnit = getOrCreateFile(Loc);
  1148. unsigned PLine = getLineNumber(Loc);
  1149. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1150. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1151. llvm::MDNode *PropertyNode =
  1152. DBuilder.createObjCProperty(PD->getName(),
  1153. PUnit, PLine,
  1154. (Getter && Getter->isImplicit()) ? "" :
  1155. getSelectorName(PD->getGetterName()),
  1156. (Setter && Setter->isImplicit()) ? "" :
  1157. getSelectorName(PD->getSetterName()),
  1158. PD->getPropertyAttributes(),
  1159. getOrCreateType(PD->getType(), PUnit));
  1160. EltTys.push_back(PropertyNode);
  1161. }
  1162. const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
  1163. unsigned FieldNo = 0;
  1164. for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
  1165. Field = Field->getNextIvar(), ++FieldNo) {
  1166. llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
  1167. if (!FieldTy.isValid())
  1168. return llvm::DIType();
  1169. StringRef FieldName = Field->getName();
  1170. // Ignore unnamed fields.
  1171. if (FieldName.empty())
  1172. continue;
  1173. // Get the location for the field.
  1174. llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
  1175. unsigned FieldLine = getLineNumber(Field->getLocation());
  1176. QualType FType = Field->getType();
  1177. uint64_t FieldSize = 0;
  1178. unsigned FieldAlign = 0;
  1179. if (!FType->isIncompleteArrayType()) {
  1180. // Bit size, align and offset of the type.
  1181. FieldSize = Field->isBitField()
  1182. ? Field->getBitWidthValue(CGM.getContext())
  1183. : CGM.getContext().getTypeSize(FType);
  1184. FieldAlign = CGM.getContext().getTypeAlign(FType);
  1185. }
  1186. // We can't know the offset of our ivar in the structure if we're using
  1187. // the non-fragile abi and the debugger should ignore the value anyways.
  1188. // Call it the FieldNo+1 due to how debuggers use the information,
  1189. // e.g. negating the value when it needs a lookup in the dynamic table.
  1190. uint64_t FieldOffset = CGM.getLangOpts().ObjCNonFragileABI ? FieldNo+1
  1191. : RL.getFieldOffset(FieldNo);
  1192. unsigned Flags = 0;
  1193. if (Field->getAccessControl() == ObjCIvarDecl::Protected)
  1194. Flags = llvm::DIDescriptor::FlagProtected;
  1195. else if (Field->getAccessControl() == ObjCIvarDecl::Private)
  1196. Flags = llvm::DIDescriptor::FlagPrivate;
  1197. llvm::MDNode *PropertyNode = NULL;
  1198. if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
  1199. if (ObjCPropertyImplDecl *PImpD =
  1200. ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
  1201. if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
  1202. SourceLocation Loc = PD->getLocation();
  1203. llvm::DIFile PUnit = getOrCreateFile(Loc);
  1204. unsigned PLine = getLineNumber(Loc);
  1205. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1206. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1207. PropertyNode =
  1208. DBuilder.createObjCProperty(PD->getName(),
  1209. PUnit, PLine,
  1210. (Getter && Getter->isImplicit()) ? "" :
  1211. getSelectorName(PD->getGetterName()),
  1212. (Setter && Setter->isImplicit()) ? "" :
  1213. getSelectorName(PD->getSetterName()),
  1214. PD->getPropertyAttributes(),
  1215. getOrCreateType(PD->getType(), PUnit));
  1216. }
  1217. }
  1218. }
  1219. FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
  1220. FieldLine, FieldSize, FieldAlign,
  1221. FieldOffset, Flags, FieldTy,
  1222. PropertyNode);
  1223. EltTys.push_back(FieldTy);
  1224. }
  1225. llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
  1226. FwdDeclNode->replaceOperandWith(10, Elements);
  1227. LexicalBlockStack.pop_back();
  1228. return llvm::DIType(FwdDeclNode);
  1229. }
  1230. llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
  1231. llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
  1232. int64_t NumElems = Ty->getNumElements();
  1233. int64_t LowerBound = 0;
  1234. if (NumElems == 0)
  1235. // If number of elements are not known then this is an unbounded array.
  1236. // Use Low = 1, Hi = 0 to express such arrays.
  1237. LowerBound = 1;
  1238. else
  1239. --NumElems;
  1240. llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
  1241. llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
  1242. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1243. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1244. return
  1245. DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
  1246. }
  1247. llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
  1248. llvm::DIFile Unit) {
  1249. uint64_t Size;
  1250. uint64_t Align;
  1251. // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
  1252. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
  1253. Size = 0;
  1254. Align =
  1255. CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
  1256. } else if (Ty->isIncompleteArrayType()) {
  1257. Size = 0;
  1258. Align = CGM.getContext().getTypeAlign(Ty->getElementType());
  1259. } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
  1260. Size = 0;
  1261. Align = 0;
  1262. } else {
  1263. // Size and align of the whole array, not the element type.
  1264. Size = CGM.getContext().getTypeSize(Ty);
  1265. Align = CGM.getContext().getTypeAlign(Ty);
  1266. }
  1267. // Add the dimensions of the array. FIXME: This loses CV qualifiers from
  1268. // interior arrays, do we care? Why aren't nested arrays represented the
  1269. // obvious/recursive way?
  1270. SmallVector<llvm::Value *, 8> Subscripts;
  1271. QualType EltTy(Ty, 0);
  1272. if (Ty->isIncompleteArrayType())
  1273. EltTy = Ty->getElementType();
  1274. else {
  1275. while ((Ty = dyn_cast<ArrayType>(EltTy))) {
  1276. int64_t UpperBound = 0;
  1277. int64_t LowerBound = 0;
  1278. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
  1279. if (CAT->getSize().getZExtValue())
  1280. UpperBound = CAT->getSize().getZExtValue() - 1;
  1281. } else
  1282. // This is an unbounded array. Use Low = 1, Hi = 0 to express such
  1283. // arrays.
  1284. LowerBound = 1;
  1285. // FIXME: Verify this is right for VLAs.
  1286. Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
  1287. UpperBound));
  1288. EltTy = Ty->getElementType();
  1289. }
  1290. }
  1291. llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
  1292. llvm::DIType DbgTy =
  1293. DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
  1294. SubscriptArray);
  1295. return DbgTy;
  1296. }
  1297. llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
  1298. llvm::DIFile Unit) {
  1299. return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
  1300. Ty, Ty->getPointeeType(), Unit);
  1301. }
  1302. llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
  1303. llvm::DIFile Unit) {
  1304. return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
  1305. Ty, Ty->getPointeeType(), Unit);
  1306. }
  1307. llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
  1308. llvm::DIFile U) {
  1309. QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
  1310. llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
  1311. if (!Ty->getPointeeType()->isFunctionType()) {
  1312. // We have a data member pointer type.
  1313. return PointerDiffDITy;
  1314. }
  1315. // We have a member function pointer type. Treat it as a struct with two
  1316. // ptrdiff_t members.
  1317. std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
  1318. uint64_t FieldOffset = 0;
  1319. llvm::Value *ElementTypes[2];
  1320. // FIXME: This should probably be a function type instead.
  1321. ElementTypes[0] =
  1322. DBuilder.createMemberType(U, "ptr", U, 0,
  1323. Info.first, Info.second, FieldOffset, 0,
  1324. PointerDiffDITy);
  1325. FieldOffset += Info.first;
  1326. ElementTypes[1] =
  1327. DBuilder.createMemberType(U, "ptr", U, 0,
  1328. Info.first, Info.second, FieldOffset, 0,
  1329. PointerDiffDITy);
  1330. llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
  1331. return DBuilder.createStructType(U, StringRef("test"),
  1332. U, 0, FieldOffset,
  1333. 0, 0, Elements);
  1334. }
  1335. llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
  1336. llvm::DIFile U) {
  1337. // Ignore the atomic wrapping
  1338. // FIXME: What is the correct representation?
  1339. return getOrCreateType(Ty->getValueType(), U);
  1340. }
  1341. /// CreateEnumType - get enumeration type.
  1342. llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
  1343. llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
  1344. SmallVector<llvm::Value *, 16> Enumerators;
  1345. // Create DIEnumerator elements for each enumerator.
  1346. for (EnumDecl::enumerator_iterator
  1347. Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
  1348. Enum != EnumEnd; ++Enum) {
  1349. Enumerators.push_back(
  1350. DBuilder.createEnumerator(Enum->getName(),
  1351. Enum->getInitVal().getZExtValue()));
  1352. }
  1353. // Return a CompositeType for the enum itself.
  1354. llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
  1355. llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
  1356. unsigned Line = getLineNumber(ED->getLocation());
  1357. uint64_t Size = 0;
  1358. uint64_t Align = 0;
  1359. if (!ED->getTypeForDecl()->isIncompleteType()) {
  1360. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  1361. Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
  1362. }
  1363. llvm::DIDescriptor EnumContext =
  1364. getContextDescriptor(cast<Decl>(ED->getDeclContext()));
  1365. llvm::DIType DbgTy =
  1366. DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
  1367. Size, Align, EltArray);
  1368. return DbgTy;
  1369. }
  1370. static QualType UnwrapTypeForDebugInfo(QualType T) {
  1371. do {
  1372. QualType LastT = T;
  1373. switch (T->getTypeClass()) {
  1374. default:
  1375. return T;
  1376. case Type::TemplateSpecialization:
  1377. T = cast<TemplateSpecializationType>(T)->desugar();
  1378. break;
  1379. case Type::TypeOfExpr:
  1380. T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
  1381. break;
  1382. case Type::TypeOf:
  1383. T = cast<TypeOfType>(T)->getUnderlyingType();
  1384. break;
  1385. case Type::Decltype:
  1386. T = cast<DecltypeType>(T)->getUnderlyingType();
  1387. break;
  1388. case Type::UnaryTransform:
  1389. T = cast<UnaryTransformType>(T)->getUnderlyingType();
  1390. break;
  1391. case Type::Attributed:
  1392. T = cast<AttributedType>(T)->getEquivalentType();
  1393. break;
  1394. case Type::Elaborated:
  1395. T = cast<ElaboratedType>(T)->getNamedType();
  1396. break;
  1397. case Type::Paren:
  1398. T = cast<ParenType>(T)->getInnerType();
  1399. break;
  1400. case Type::SubstTemplateTypeParm:
  1401. T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
  1402. break;
  1403. case Type::Auto:
  1404. T = cast<AutoType>(T)->getDeducedType();
  1405. break;
  1406. }
  1407. assert(T != LastT && "Type unwrapping failed to unwrap!");
  1408. if (T == LastT)
  1409. return T;
  1410. } while (true);
  1411. }
  1412. /// getType - Get the type from the cache or return null type if it doesn't exist.
  1413. llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
  1414. // Unwrap the type as needed for debug information.
  1415. Ty = UnwrapTypeForDebugInfo(Ty);
  1416. // Check for existing entry.
  1417. llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
  1418. TypeCache.find(Ty.getAsOpaquePtr());
  1419. if (it != TypeCache.end()) {
  1420. // Verify that the debug info still exists.
  1421. if (&*it->second)
  1422. return llvm::DIType(cast<llvm::MDNode>(it->second));
  1423. }
  1424. return llvm::DIType();
  1425. }
  1426. /// getCompletedTypeOrNull - Get the type from the cache or return null if it
  1427. /// doesn't exist.
  1428. llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
  1429. // Unwrap the type as needed for debug information.
  1430. Ty = UnwrapTypeForDebugInfo(Ty);
  1431. // Check for existing entry.
  1432. llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
  1433. CompletedTypeCache.find(Ty.getAsOpaquePtr());
  1434. if (it != CompletedTypeCache.end()) {
  1435. // Verify that the debug info still exists.
  1436. if (&*it->second)
  1437. return llvm::DIType(cast<llvm::MDNode>(it->second));
  1438. }
  1439. return llvm::DIType();
  1440. }
  1441. /// getOrCreateType - Get the type from the cache or create a new
  1442. /// one if necessary.
  1443. llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
  1444. if (Ty.isNull())
  1445. return llvm::DIType();
  1446. // Unwrap the type as needed for debug information.
  1447. Ty = UnwrapTypeForDebugInfo(Ty);
  1448. llvm::DIType T = getCompletedTypeOrNull(Ty);
  1449. if (T.Verify()) return T;
  1450. // Otherwise create the type.
  1451. llvm::DIType Res = CreateTypeNode(Ty, Unit);
  1452. llvm::DIType TC = getTypeOrNull(Ty);
  1453. if (TC.Verify() && TC.isForwardDecl())
  1454. ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), TC));
  1455. // And update the type cache.
  1456. TypeCache[Ty.getAsOpaquePtr()] = Res;
  1457. if (!Res.isForwardDecl())
  1458. CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
  1459. return Res;
  1460. }
  1461. /// CreateTypeNode - Create a new debug type node.
  1462. llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
  1463. // Handle qualifiers, which recursively handles what they refer to.
  1464. if (Ty.hasLocalQualifiers())
  1465. return CreateQualifiedType(Ty, Unit);
  1466. const char *Diag = 0;
  1467. // Work out details of type.
  1468. switch (Ty->getTypeClass()) {
  1469. #define TYPE(Class, Base)
  1470. #define ABSTRACT_TYPE(Class, Base)
  1471. #define NON_CANONICAL_TYPE(Class, Base)
  1472. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1473. #include "clang/AST/TypeNodes.def"
  1474. llvm_unreachable("Dependent types cannot show up in debug information");
  1475. case Type::ExtVector:
  1476. case Type::Vector:
  1477. return CreateType(cast<VectorType>(Ty), Unit);
  1478. case Type::ObjCObjectPointer:
  1479. return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
  1480. case Type::ObjCObject:
  1481. return CreateType(cast<ObjCObjectType>(Ty), Unit);
  1482. case Type::ObjCInterface:
  1483. return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
  1484. case Type::Builtin:
  1485. return CreateType(cast<BuiltinType>(Ty));
  1486. case Type::Complex:
  1487. return CreateType(cast<ComplexType>(Ty));
  1488. case Type::Pointer:
  1489. return CreateType(cast<PointerType>(Ty), Unit);
  1490. case Type::BlockPointer:
  1491. return CreateType(cast<BlockPointerType>(Ty), Unit);
  1492. case Type::Typedef:
  1493. return CreateType(cast<TypedefType>(Ty), Unit);
  1494. case Type::Record:
  1495. return CreateType(cast<RecordType>(Ty));
  1496. case Type::Enum:
  1497. return CreateEnumType(cast<EnumType>(Ty)->getDecl());
  1498. case Type::FunctionProto:
  1499. case Type::FunctionNoProto:
  1500. return CreateType(cast<FunctionType>(Ty), Unit);
  1501. case Type::ConstantArray:
  1502. case Type::VariableArray:
  1503. case Type::IncompleteArray:
  1504. return CreateType(cast<ArrayType>(Ty), Unit);
  1505. case Type::LValueReference:
  1506. return CreateType(cast<LValueReferenceType>(Ty), Unit);
  1507. case Type::RValueReference:
  1508. return CreateType(cast<RValueReferenceType>(Ty), Unit);
  1509. case Type::MemberPointer:
  1510. return CreateType(cast<MemberPointerType>(Ty), Unit);
  1511. case Type::Atomic:
  1512. return CreateType(cast<AtomicType>(Ty), Unit);
  1513. case Type::Attributed:
  1514. case Type::TemplateSpecialization:
  1515. case Type::Elaborated:
  1516. case Type::Paren:
  1517. case Type::SubstTemplateTypeParm:
  1518. case Type::TypeOfExpr:
  1519. case Type::TypeOf:
  1520. case Type::Decltype:
  1521. case Type::UnaryTransform:
  1522. case Type::Auto:
  1523. llvm_unreachable("type should have been unwrapped!");
  1524. }
  1525. assert(Diag && "Fall through without a diagnostic?");
  1526. unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  1527. "debug information for %0 is not yet supported");
  1528. CGM.getDiags().Report(DiagID)
  1529. << Diag;
  1530. return llvm::DIType();
  1531. }
  1532. /// getOrCreateLimitedType - Get the type from the cache or create a new
  1533. /// limited type if necessary.
  1534. llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
  1535. llvm::DIFile Unit) {
  1536. if (Ty.isNull())
  1537. return llvm::DIType();
  1538. // Unwrap the type as needed for debug information.
  1539. Ty = UnwrapTypeForDebugInfo(Ty);
  1540. llvm::DIType T = getTypeOrNull(Ty);
  1541. // We may have cached a forward decl when we could have created
  1542. // a non-forward decl. Go ahead and create a non-forward decl
  1543. // now.
  1544. if (T.Verify() && !T.isForwardDecl()) return T;
  1545. // Otherwise create the type.
  1546. llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
  1547. if (T.Verify() && T.isForwardDecl())
  1548. ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), T));
  1549. // And update the type cache.
  1550. TypeCache[Ty.getAsOpaquePtr()] = Res;
  1551. return Res;
  1552. }
  1553. // TODO: Currently used for context chains when limiting debug info.
  1554. llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
  1555. RecordDecl *RD = Ty->getDecl();
  1556. // Get overall information about the record type for the debug info.
  1557. llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
  1558. unsigned Line = getLineNumber(RD->getLocation());
  1559. StringRef RDName = RD->getName();
  1560. llvm::DIDescriptor RDContext;
  1561. if (CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo)
  1562. RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
  1563. else
  1564. RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
  1565. // If this is just a forward declaration, construct an appropriately
  1566. // marked node and just return it.
  1567. if (!RD->getDefinition())
  1568. return createRecordFwdDecl(RD, RDContext);
  1569. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1570. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1571. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1572. llvm::TrackingVH<llvm::MDNode> RealDecl;
  1573. if (RD->isUnion())
  1574. RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
  1575. Size, Align, 0, llvm::DIArray());
  1576. else if (CXXDecl) {
  1577. RDName = getClassName(RD);
  1578. // FIXME: This could be a struct type giving a default visibility different
  1579. // than C++ class type, but needs llvm metadata changes first.
  1580. RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
  1581. Size, Align, 0, 0, llvm::DIType(),
  1582. llvm::DIArray(), llvm::DIType(),
  1583. llvm::DIArray());
  1584. } else
  1585. RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
  1586. Size, Align, 0, llvm::DIArray());
  1587. RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
  1588. TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
  1589. if (CXXDecl) {
  1590. // A class's primary base or the class itself contains the vtable.
  1591. llvm::MDNode *ContainingType = NULL;
  1592. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1593. if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
  1594. // Seek non virtual primary base root.
  1595. while (1) {
  1596. const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
  1597. const CXXRecordDecl *PBT = BRL.getPrimaryBase();
  1598. if (PBT && !BRL.isPrimaryBaseVirtual())
  1599. PBase = PBT;
  1600. else
  1601. break;
  1602. }
  1603. ContainingType =
  1604. getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
  1605. }
  1606. else if (CXXDecl->isDynamicClass())
  1607. ContainingType = RealDecl;
  1608. RealDecl->replaceOperandWith(12, ContainingType);
  1609. }
  1610. return llvm::DIType(RealDecl);
  1611. }
  1612. /// CreateLimitedTypeNode - Create a new debug type node, but only forward
  1613. /// declare composite types that haven't been processed yet.
  1614. llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
  1615. // Work out details of type.
  1616. switch (Ty->getTypeClass()) {
  1617. #define TYPE(Class, Base)
  1618. #define ABSTRACT_TYPE(Class, Base)
  1619. #define NON_CANONICAL_TYPE(Class, Base)
  1620. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1621. #include "clang/AST/TypeNodes.def"
  1622. llvm_unreachable("Dependent types cannot show up in debug information");
  1623. case Type::Record:
  1624. return CreateLimitedType(cast<RecordType>(Ty));
  1625. default:
  1626. return CreateTypeNode(Ty, Unit);
  1627. }
  1628. }
  1629. /// CreateMemberType - Create new member and increase Offset by FType's size.
  1630. llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
  1631. StringRef Name,
  1632. uint64_t *Offset) {
  1633. llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
  1634. uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
  1635. unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
  1636. llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
  1637. FieldSize, FieldAlign,
  1638. *Offset, 0, FieldTy);
  1639. *Offset += FieldSize;
  1640. return Ty;
  1641. }
  1642. /// getFunctionDeclaration - Return debug info descriptor to describe method
  1643. /// declaration for the given method definition.
  1644. llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
  1645. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  1646. if (!FD) return llvm::DISubprogram();
  1647. // Setup context.
  1648. getContextDescriptor(cast<Decl>(D->getDeclContext()));
  1649. llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
  1650. MI = SPCache.find(FD->getCanonicalDecl());
  1651. if (MI != SPCache.end()) {
  1652. llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
  1653. if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
  1654. return SP;
  1655. }
  1656. for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
  1657. E = FD->redecls_end(); I != E; ++I) {
  1658. const FunctionDecl *NextFD = *I;
  1659. llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
  1660. MI = SPCache.find(NextFD->getCanonicalDecl());
  1661. if (MI != SPCache.end()) {
  1662. llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
  1663. if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
  1664. return SP;
  1665. }
  1666. }
  1667. return llvm::DISubprogram();
  1668. }
  1669. // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
  1670. // implicit parameter "this".
  1671. llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
  1672. QualType FnType,
  1673. llvm::DIFile F) {
  1674. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1675. return getOrCreateMethodType(Method, F);
  1676. if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
  1677. // Add "self" and "_cmd"
  1678. SmallVector<llvm::Value *, 16> Elts;
  1679. // First element is always return type. For 'void' functions it is NULL.
  1680. Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
  1681. // "self" pointer is always first argument.
  1682. Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
  1683. // "cmd" pointer is always second argument.
  1684. Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
  1685. // Get rest of the arguments.
  1686. for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
  1687. PE = OMethod->param_end(); PI != PE; ++PI)
  1688. Elts.push_back(getOrCreateType((*PI)->getType(), F));
  1689. llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
  1690. return DBuilder.createSubroutineType(F, EltTypeArray);
  1691. }
  1692. return getOrCreateType(FnType, F);
  1693. }
  1694. /// EmitFunctionStart - Constructs the debug code for entering a function.
  1695. void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
  1696. llvm::Function *Fn,
  1697. CGBuilderTy &Builder) {
  1698. StringRef Name;
  1699. StringRef LinkageName;
  1700. FnBeginRegionCount.push_back(LexicalBlockStack.size());
  1701. const Decl *D = GD.getDecl();
  1702. // Use the location of the declaration.
  1703. SourceLocation Loc = D->getLocation();
  1704. unsigned Flags = 0;
  1705. llvm::DIFile Unit = getOrCreateFile(Loc);
  1706. llvm::DIDescriptor FDContext(Unit);
  1707. llvm::DIArray TParamsArray;
  1708. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1709. // If there is a DISubprogram for this function available then use it.
  1710. llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
  1711. FI = SPCache.find(FD->getCanonicalDecl());
  1712. if (FI != SPCache.end()) {
  1713. llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
  1714. if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
  1715. llvm::MDNode *SPN = SP;
  1716. LexicalBlockStack.push_back(SPN);
  1717. RegionMap[D] = llvm::WeakVH(SP);
  1718. return;
  1719. }
  1720. }
  1721. Name = getFunctionName(FD);
  1722. // Use mangled name as linkage name for c/c++ functions.
  1723. if (FD->hasPrototype()) {
  1724. LinkageName = CGM.getMangledName(GD);
  1725. Flags |= llvm::DIDescriptor::FlagPrototyped;
  1726. }
  1727. if (LinkageName == Name)
  1728. LinkageName = StringRef();
  1729. if (const NamespaceDecl *NSDecl =
  1730. dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
  1731. FDContext = getOrCreateNameSpace(NSDecl);
  1732. else if (const RecordDecl *RDecl =
  1733. dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
  1734. FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
  1735. // Collect template parameters.
  1736. TParamsArray = CollectFunctionTemplateParams(FD, Unit);
  1737. } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  1738. Name = getObjCMethodName(OMD);
  1739. Flags |= llvm::DIDescriptor::FlagPrototyped;
  1740. } else {
  1741. // Use llvm function name.
  1742. Name = Fn->getName();
  1743. Flags |= llvm::DIDescriptor::FlagPrototyped;
  1744. }
  1745. if (!Name.empty() && Name[0] == '\01')
  1746. Name = Name.substr(1);
  1747. unsigned LineNo = getLineNumber(Loc);
  1748. if (D->isImplicit())
  1749. Flags |= llvm::DIDescriptor::FlagArtificial;
  1750. llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
  1751. llvm::DISubprogram SP =
  1752. DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
  1753. LineNo, getOrCreateFunctionType(D, FnType, Unit),
  1754. Fn->hasInternalLinkage(), true/*definition*/,
  1755. getLineNumber(CurLoc),
  1756. Flags, CGM.getLangOpts().Optimize, Fn,
  1757. TParamsArray, SPDecl);
  1758. // Push function on region stack.
  1759. llvm::MDNode *SPN = SP;
  1760. LexicalBlockStack.push_back(SPN);
  1761. RegionMap[D] = llvm::WeakVH(SP);
  1762. }
  1763. /// EmitLocation - Emit metadata to indicate a change in line/column
  1764. /// information in the source file.
  1765. void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
  1766. // Update our current location
  1767. setLocation(Loc);
  1768. if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
  1769. // Don't bother if things are the same as last time.
  1770. SourceManager &SM = CGM.getContext().getSourceManager();
  1771. if (CurLoc == PrevLoc ||
  1772. SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
  1773. // New Builder may not be in sync with CGDebugInfo.
  1774. if (!Builder.getCurrentDebugLocation().isUnknown())
  1775. return;
  1776. // Update last state.
  1777. PrevLoc = CurLoc;
  1778. llvm::MDNode *Scope = LexicalBlockStack.back();
  1779. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
  1780. getColumnNumber(CurLoc),
  1781. Scope));
  1782. }
  1783. /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
  1784. /// the stack.
  1785. void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
  1786. llvm::DIDescriptor D =
  1787. DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
  1788. llvm::DIDescriptor() :
  1789. llvm::DIDescriptor(LexicalBlockStack.back()),
  1790. getOrCreateFile(CurLoc),
  1791. getLineNumber(CurLoc),
  1792. getColumnNumber(CurLoc));
  1793. llvm::MDNode *DN = D;
  1794. LexicalBlockStack.push_back(DN);
  1795. }
  1796. /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
  1797. /// region - beginning of a DW_TAG_lexical_block.
  1798. void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
  1799. // Set our current location.
  1800. setLocation(Loc);
  1801. // Create a new lexical block and push it on the stack.
  1802. CreateLexicalBlock(Loc);
  1803. // Emit a line table change for the current location inside the new scope.
  1804. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
  1805. getColumnNumber(Loc),
  1806. LexicalBlockStack.back()));
  1807. }
  1808. /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
  1809. /// region - end of a DW_TAG_lexical_block.
  1810. void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
  1811. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  1812. // Provide an entry in the line table for the end of the block.
  1813. EmitLocation(Builder, Loc);
  1814. LexicalBlockStack.pop_back();
  1815. }
  1816. /// EmitFunctionEnd - Constructs the debug code for exiting a function.
  1817. void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
  1818. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  1819. unsigned RCount = FnBeginRegionCount.back();
  1820. assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
  1821. // Pop all regions for this function.
  1822. while (LexicalBlockStack.size() != RCount)
  1823. EmitLexicalBlockEnd(Builder, CurLoc);
  1824. FnBeginRegionCount.pop_back();
  1825. }
  1826. // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
  1827. // See BuildByRefType.
  1828. llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
  1829. uint64_t *XOffset) {
  1830. SmallVector<llvm::Value *, 5> EltTys;
  1831. QualType FType;
  1832. uint64_t FieldSize, FieldOffset;
  1833. unsigned FieldAlign;
  1834. llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
  1835. QualType Type = VD->getType();
  1836. FieldOffset = 0;
  1837. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  1838. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  1839. EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
  1840. FType = CGM.getContext().IntTy;
  1841. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  1842. EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
  1843. bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
  1844. if (HasCopyAndDispose) {
  1845. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  1846. EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
  1847. &FieldOffset));
  1848. EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
  1849. &FieldOffset));
  1850. }
  1851. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  1852. if (Align > CGM.getContext().toCharUnitsFromBits(
  1853. CGM.getContext().getTargetInfo().getPointerAlign(0))) {
  1854. CharUnits FieldOffsetInBytes
  1855. = CGM.getContext().toCharUnitsFromBits(FieldOffset);
  1856. CharUnits AlignedOffsetInBytes
  1857. = FieldOffsetInBytes.RoundUpToAlignment(Align);
  1858. CharUnits NumPaddingBytes
  1859. = AlignedOffsetInBytes - FieldOffsetInBytes;
  1860. if (NumPaddingBytes.isPositive()) {
  1861. llvm::APInt pad(32, NumPaddingBytes.getQuantity());
  1862. FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
  1863. pad, ArrayType::Normal, 0);
  1864. EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
  1865. }
  1866. }
  1867. FType = Type;
  1868. llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
  1869. FieldSize = CGM.getContext().getTypeSize(FType);
  1870. FieldAlign = CGM.getContext().toBits(Align);
  1871. *XOffset = FieldOffset;
  1872. FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
  1873. 0, FieldSize, FieldAlign,
  1874. FieldOffset, 0, FieldTy);
  1875. EltTys.push_back(FieldTy);
  1876. FieldOffset += FieldSize;
  1877. llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
  1878. unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
  1879. return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
  1880. Elements);
  1881. }
  1882. /// EmitDeclare - Emit local variable declaration debug info.
  1883. void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
  1884. llvm::Value *Storage,
  1885. unsigned ArgNo, CGBuilderTy &Builder) {
  1886. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  1887. llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
  1888. llvm::DIType Ty;
  1889. uint64_t XOffset = 0;
  1890. if (VD->hasAttr<BlocksAttr>())
  1891. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  1892. else
  1893. Ty = getOrCreateType(VD->getType(), Unit);
  1894. // If there is not any debug info for type then do not emit debug info
  1895. // for this variable.
  1896. if (!Ty)
  1897. return;
  1898. if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
  1899. // If Storage is an aggregate returned as 'sret' then let debugger know
  1900. // about this.
  1901. if (Arg->hasStructRetAttr())
  1902. Ty = DBuilder.createReferenceType(Ty);
  1903. else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
  1904. // If an aggregate variable has non trivial destructor or non trivial copy
  1905. // constructor than it is pass indirectly. Let debug info know about this
  1906. // by using reference of the aggregate type as a argument type.
  1907. if (!Record->hasTrivialCopyConstructor() ||
  1908. !Record->hasTrivialDestructor())
  1909. Ty = DBuilder.createReferenceType(Ty);
  1910. }
  1911. }
  1912. // Get location information.
  1913. unsigned Line = getLineNumber(VD->getLocation());
  1914. unsigned Column = getColumnNumber(VD->getLocation());
  1915. unsigned Flags = 0;
  1916. if (VD->isImplicit())
  1917. Flags |= llvm::DIDescriptor::FlagArtificial;
  1918. llvm::MDNode *Scope = LexicalBlockStack.back();
  1919. StringRef Name = VD->getName();
  1920. if (!Name.empty()) {
  1921. if (VD->hasAttr<BlocksAttr>()) {
  1922. CharUnits offset = CharUnits::fromQuantity(32);
  1923. SmallVector<llvm::Value *, 9> addr;
  1924. llvm::Type *Int64Ty = CGM.Int64Ty;
  1925. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
  1926. // offset of __forwarding field
  1927. offset = CGM.getContext().toCharUnitsFromBits(
  1928. CGM.getContext().getTargetInfo().getPointerWidth(0));
  1929. addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
  1930. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
  1931. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
  1932. // offset of x field
  1933. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  1934. addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
  1935. // Create the descriptor for the variable.
  1936. llvm::DIVariable D =
  1937. DBuilder.createComplexVariable(Tag,
  1938. llvm::DIDescriptor(Scope),
  1939. VD->getName(), Unit, Line, Ty,
  1940. addr, ArgNo);
  1941. // Insert an llvm.dbg.declare into the current block.
  1942. llvm::Instruction *Call =
  1943. DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
  1944. Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
  1945. return;
  1946. }
  1947. // Create the descriptor for the variable.
  1948. llvm::DIVariable D =
  1949. DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
  1950. Name, Unit, Line, Ty,
  1951. CGM.getLangOpts().Optimize, Flags, ArgNo);
  1952. // Insert an llvm.dbg.declare into the current block.
  1953. llvm::Instruction *Call =
  1954. DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
  1955. Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
  1956. return;
  1957. }
  1958. // If VD is an anonymous union then Storage represents value for
  1959. // all union fields.
  1960. if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
  1961. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1962. if (RD->isUnion()) {
  1963. for (RecordDecl::field_iterator I = RD->field_begin(),
  1964. E = RD->field_end();
  1965. I != E; ++I) {
  1966. FieldDecl *Field = &*I;
  1967. llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
  1968. StringRef FieldName = Field->getName();
  1969. // Ignore unnamed fields. Do not ignore unnamed records.
  1970. if (FieldName.empty() && !isa<RecordType>(Field->getType()))
  1971. continue;
  1972. // Use VarDecl's Tag, Scope and Line number.
  1973. llvm::DIVariable D =
  1974. DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
  1975. FieldName, Unit, Line, FieldTy,
  1976. CGM.getLangOpts().Optimize, Flags,
  1977. ArgNo);
  1978. // Insert an llvm.dbg.declare into the current block.
  1979. llvm::Instruction *Call =
  1980. DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
  1981. Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
  1982. }
  1983. }
  1984. }
  1985. }
  1986. void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
  1987. llvm::Value *Storage,
  1988. CGBuilderTy &Builder) {
  1989. EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
  1990. }
  1991. void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
  1992. const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
  1993. const CGBlockInfo &blockInfo) {
  1994. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  1995. if (Builder.GetInsertBlock() == 0)
  1996. return;
  1997. bool isByRef = VD->hasAttr<BlocksAttr>();
  1998. uint64_t XOffset = 0;
  1999. llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
  2000. llvm::DIType Ty;
  2001. if (isByRef)
  2002. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2003. else
  2004. Ty = getOrCreateType(VD->getType(), Unit);
  2005. // Get location information.
  2006. unsigned Line = getLineNumber(VD->getLocation());
  2007. unsigned Column = getColumnNumber(VD->getLocation());
  2008. const llvm::TargetData &target = CGM.getTargetData();
  2009. CharUnits offset = CharUnits::fromQuantity(
  2010. target.getStructLayout(blockInfo.StructureType)
  2011. ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
  2012. SmallVector<llvm::Value *, 9> addr;
  2013. llvm::Type *Int64Ty = CGM.Int64Ty;
  2014. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
  2015. addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
  2016. if (isByRef) {
  2017. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
  2018. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
  2019. // offset of __forwarding field
  2020. offset = CGM.getContext()
  2021. .toCharUnitsFromBits(target.getPointerSizeInBits());
  2022. addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
  2023. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
  2024. addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
  2025. // offset of x field
  2026. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2027. addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
  2028. }
  2029. // Create the descriptor for the variable.
  2030. llvm::DIVariable D =
  2031. DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
  2032. llvm::DIDescriptor(LexicalBlockStack.back()),
  2033. VD->getName(), Unit, Line, Ty, addr);
  2034. // Insert an llvm.dbg.declare into the current block.
  2035. llvm::Instruction *Call =
  2036. DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
  2037. Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
  2038. LexicalBlockStack.back()));
  2039. }
  2040. /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
  2041. /// variable declaration.
  2042. void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
  2043. unsigned ArgNo,
  2044. CGBuilderTy &Builder) {
  2045. EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
  2046. }
  2047. namespace {
  2048. struct BlockLayoutChunk {
  2049. uint64_t OffsetInBits;
  2050. const BlockDecl::Capture *Capture;
  2051. };
  2052. bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
  2053. return l.OffsetInBits < r.OffsetInBits;
  2054. }
  2055. }
  2056. void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
  2057. llvm::Value *addr,
  2058. CGBuilderTy &Builder) {
  2059. ASTContext &C = CGM.getContext();
  2060. const BlockDecl *blockDecl = block.getBlockDecl();
  2061. // Collect some general information about the block's location.
  2062. SourceLocation loc = blockDecl->getCaretLocation();
  2063. llvm::DIFile tunit = getOrCreateFile(loc);
  2064. unsigned line = getLineNumber(loc);
  2065. unsigned column = getColumnNumber(loc);
  2066. // Build the debug-info type for the block literal.
  2067. getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
  2068. const llvm::StructLayout *blockLayout =
  2069. CGM.getTargetData().getStructLayout(block.StructureType);
  2070. SmallVector<llvm::Value*, 16> fields;
  2071. fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
  2072. blockLayout->getElementOffsetInBits(0),
  2073. tunit, tunit));
  2074. fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
  2075. blockLayout->getElementOffsetInBits(1),
  2076. tunit, tunit));
  2077. fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
  2078. blockLayout->getElementOffsetInBits(2),
  2079. tunit, tunit));
  2080. fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
  2081. blockLayout->getElementOffsetInBits(3),
  2082. tunit, tunit));
  2083. fields.push_back(createFieldType("__descriptor",
  2084. C.getPointerType(block.NeedsCopyDispose ?
  2085. C.getBlockDescriptorExtendedType() :
  2086. C.getBlockDescriptorType()),
  2087. 0, loc, AS_public,
  2088. blockLayout->getElementOffsetInBits(4),
  2089. tunit, tunit));
  2090. // We want to sort the captures by offset, not because DWARF
  2091. // requires this, but because we're paranoid about debuggers.
  2092. SmallVector<BlockLayoutChunk, 8> chunks;
  2093. // 'this' capture.
  2094. if (blockDecl->capturesCXXThis()) {
  2095. BlockLayoutChunk chunk;
  2096. chunk.OffsetInBits =
  2097. blockLayout->getElementOffsetInBits(block.CXXThisIndex);
  2098. chunk.Capture = 0;
  2099. chunks.push_back(chunk);
  2100. }
  2101. // Variable captures.
  2102. for (BlockDecl::capture_const_iterator
  2103. i = blockDecl->capture_begin(), e = blockDecl->capture_end();
  2104. i != e; ++i) {
  2105. const BlockDecl::Capture &capture = *i;
  2106. const VarDecl *variable = capture.getVariable();
  2107. const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
  2108. // Ignore constant captures.
  2109. if (captureInfo.isConstant())
  2110. continue;
  2111. BlockLayoutChunk chunk;
  2112. chunk.OffsetInBits =
  2113. blockLayout->getElementOffsetInBits(captureInfo.getIndex());
  2114. chunk.Capture = &capture;
  2115. chunks.push_back(chunk);
  2116. }
  2117. // Sort by offset.
  2118. llvm::array_pod_sort(chunks.begin(), chunks.end());
  2119. for (SmallVectorImpl<BlockLayoutChunk>::iterator
  2120. i = chunks.begin(), e = chunks.end(); i != e; ++i) {
  2121. uint64_t offsetInBits = i->OffsetInBits;
  2122. const BlockDecl::Capture *capture = i->Capture;
  2123. // If we have a null capture, this must be the C++ 'this' capture.
  2124. if (!capture) {
  2125. const CXXMethodDecl *method =
  2126. cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
  2127. QualType type = method->getThisType(C);
  2128. fields.push_back(createFieldType("this", type, 0, loc, AS_public,
  2129. offsetInBits, tunit, tunit));
  2130. continue;
  2131. }
  2132. const VarDecl *variable = capture->getVariable();
  2133. StringRef name = variable->getName();
  2134. llvm::DIType fieldType;
  2135. if (capture->isByRef()) {
  2136. std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
  2137. // FIXME: this creates a second copy of this type!
  2138. uint64_t xoffset;
  2139. fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
  2140. fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
  2141. fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
  2142. ptrInfo.first, ptrInfo.second,
  2143. offsetInBits, 0, fieldType);
  2144. } else {
  2145. fieldType = createFieldType(name, variable->getType(), 0,
  2146. loc, AS_public, offsetInBits, tunit, tunit);
  2147. }
  2148. fields.push_back(fieldType);
  2149. }
  2150. SmallString<36> typeName;
  2151. llvm::raw_svector_ostream(typeName)
  2152. << "__block_literal_" << CGM.getUniqueBlockCount();
  2153. llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
  2154. llvm::DIType type =
  2155. DBuilder.createStructType(tunit, typeName.str(), tunit, line,
  2156. CGM.getContext().toBits(block.BlockSize),
  2157. CGM.getContext().toBits(block.BlockAlign),
  2158. 0, fieldsArray);
  2159. type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
  2160. // Get overall information about the block.
  2161. unsigned flags = llvm::DIDescriptor::FlagArtificial;
  2162. llvm::MDNode *scope = LexicalBlockStack.back();
  2163. StringRef name = ".block_descriptor";
  2164. // Create the descriptor for the parameter.
  2165. llvm::DIVariable debugVar =
  2166. DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
  2167. llvm::DIDescriptor(scope),
  2168. name, tunit, line, type,
  2169. CGM.getLangOpts().Optimize, flags,
  2170. cast<llvm::Argument>(addr)->getArgNo() + 1);
  2171. // Insert an llvm.dbg.value into the current block.
  2172. llvm::Instruction *declare =
  2173. DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
  2174. Builder.GetInsertBlock());
  2175. declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
  2176. }
  2177. /// EmitGlobalVariable - Emit information about a global variable.
  2178. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
  2179. const VarDecl *D) {
  2180. // Create global variable debug descriptor.
  2181. llvm::DIFile Unit = getOrCreateFile(D->getLocation());
  2182. unsigned LineNo = getLineNumber(D->getLocation());
  2183. setLocation(D->getLocation());
  2184. QualType T = D->getType();
  2185. if (T->isIncompleteArrayType()) {
  2186. // CodeGen turns int[] into int[1] so we'll do the same here.
  2187. llvm::APSInt ConstVal(32);
  2188. ConstVal = 1;
  2189. QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
  2190. T = CGM.getContext().getConstantArrayType(ET, ConstVal,
  2191. ArrayType::Normal, 0);
  2192. }
  2193. StringRef DeclName = D->getName();
  2194. StringRef LinkageName;
  2195. if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
  2196. && !isa<ObjCMethodDecl>(D->getDeclContext()))
  2197. LinkageName = Var->getName();
  2198. if (LinkageName == DeclName)
  2199. LinkageName = StringRef();
  2200. llvm::DIDescriptor DContext =
  2201. getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
  2202. DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
  2203. Unit, LineNo, getOrCreateType(T, Unit),
  2204. Var->hasInternalLinkage(), Var);
  2205. }
  2206. /// EmitGlobalVariable - Emit information about an objective-c interface.
  2207. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
  2208. ObjCInterfaceDecl *ID) {
  2209. // Create global variable debug descriptor.
  2210. llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
  2211. unsigned LineNo = getLineNumber(ID->getLocation());
  2212. StringRef Name = ID->getName();
  2213. QualType T = CGM.getContext().getObjCInterfaceType(ID);
  2214. if (T->isIncompleteArrayType()) {
  2215. // CodeGen turns int[] into int[1] so we'll do the same here.
  2216. llvm::APSInt ConstVal(32);
  2217. ConstVal = 1;
  2218. QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
  2219. T = CGM.getContext().getConstantArrayType(ET, ConstVal,
  2220. ArrayType::Normal, 0);
  2221. }
  2222. DBuilder.createGlobalVariable(Name, Unit, LineNo,
  2223. getOrCreateType(T, Unit),
  2224. Var->hasInternalLinkage(), Var);
  2225. }
  2226. /// EmitGlobalVariable - Emit global variable's debug info.
  2227. void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
  2228. llvm::Constant *Init) {
  2229. // Create the descriptor for the variable.
  2230. llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
  2231. StringRef Name = VD->getName();
  2232. llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
  2233. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
  2234. if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
  2235. Ty = CreateEnumType(ED);
  2236. }
  2237. // Do not use DIGlobalVariable for enums.
  2238. if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
  2239. return;
  2240. DBuilder.createStaticVariable(Unit, Name, Name, Unit,
  2241. getLineNumber(VD->getLocation()),
  2242. Ty, true, Init);
  2243. }
  2244. /// getOrCreateNamesSpace - Return namespace descriptor for the given
  2245. /// namespace decl.
  2246. llvm::DINameSpace
  2247. CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
  2248. llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
  2249. NameSpaceCache.find(NSDecl);
  2250. if (I != NameSpaceCache.end())
  2251. return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
  2252. unsigned LineNo = getLineNumber(NSDecl->getLocation());
  2253. llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
  2254. llvm::DIDescriptor Context =
  2255. getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
  2256. llvm::DINameSpace NS =
  2257. DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
  2258. NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
  2259. return NS;
  2260. }
  2261. void CGDebugInfo::finalize(void) {
  2262. for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
  2263. = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
  2264. llvm::DIType Ty, RepTy;
  2265. // Verify that the debug info still exists.
  2266. if (&*VI->second)
  2267. Ty = llvm::DIType(cast<llvm::MDNode>(VI->second));
  2268. llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
  2269. TypeCache.find(VI->first);
  2270. if (it != TypeCache.end()) {
  2271. // Verify that the debug info still exists.
  2272. if (&*it->second)
  2273. RepTy = llvm::DIType(cast<llvm::MDNode>(it->second));
  2274. }
  2275. if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
  2276. Ty.replaceAllUsesWith(RepTy);
  2277. }
  2278. }
  2279. DBuilder.finalize();
  2280. }