CGDebugInfo.cpp 96 KB

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