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