CGDebugInfo.cpp 96 KB

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