LCOV - code coverage report
Current view: top level - lib/CodeGen/AsmPrinter - DwarfUnit.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 766 834 91.8 %
Date: 2017-09-14 15:23:50 Functions: 82 83 98.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file contains support for constructing a dwarf compile unit.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "DwarfUnit.h"
      15             : #include "AddressPool.h"
      16             : #include "DwarfCompileUnit.h"
      17             : #include "DwarfDebug.h"
      18             : #include "DwarfExpression.h"
      19             : #include "llvm/ADT/APFloat.h"
      20             : #include "llvm/ADT/APInt.h"
      21             : #include "llvm/ADT/None.h"
      22             : #include "llvm/ADT/iterator_range.h"
      23             : #include "llvm/CodeGen/MachineFunction.h"
      24             : #include "llvm/CodeGen/MachineOperand.h"
      25             : #include "llvm/IR/Constants.h"
      26             : #include "llvm/IR/DataLayout.h"
      27             : #include "llvm/IR/GlobalValue.h"
      28             : #include "llvm/IR/Metadata.h"
      29             : #include "llvm/MC/MCAsmInfo.h"
      30             : #include "llvm/MC/MCDwarf.h"
      31             : #include "llvm/MC/MCSection.h"
      32             : #include "llvm/MC/MCStreamer.h"
      33             : #include "llvm/MC/MachineLocation.h"
      34             : #include "llvm/Support/Casting.h"
      35             : #include "llvm/Support/CommandLine.h"
      36             : #include "llvm/Target/TargetLoweringObjectFile.h"
      37             : #include "llvm/Target/TargetRegisterInfo.h"
      38             : #include "llvm/Target/TargetSubtargetInfo.h"
      39             : #include <cassert>
      40             : #include <cstdint>
      41             : #include <string>
      42             : #include <utility>
      43             : 
      44             : using namespace llvm;
      45             : 
      46             : #define DEBUG_TYPE "dwarfdebug"
      47             : 
      48             : static cl::opt<bool>
      49       72306 : GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
      50      216918 :                        cl::desc("Generate DWARF4 type units."),
      51      289224 :                        cl::init(false));
      52             : 
      53        1980 : DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
      54        1980 :                                        DIELoc &DIE)
      55        1980 :     : DwarfExpression(AP.getDwarfVersion()), AP(AP), DU(DU),
      56        5940 :       DIE(DIE) {}
      57             : 
      58        1773 : void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
      59        1773 :   DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
      60        1773 : }
      61             : 
      62         480 : void DIEDwarfExpression::emitSigned(int64_t Value) {
      63        1440 :   DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
      64         480 : }
      65             : 
      66          61 : void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
      67          61 :   DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
      68          61 : }
      69             : 
      70         533 : bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
      71             :                                          unsigned MachineReg) {
      72         533 :   return MachineReg == TRI.getFrameRegister(*AP.MF);
      73             : }
      74             : 
      75         801 : DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
      76         801 :                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
      77        1602 :     : DIEUnit(A->getDwarfVersion(), A->MAI->getCodePointerSize(), UnitTag),
      78        6408 :       CUNode(Node), Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) {
      79         801 : }
      80             : 
      81          36 : DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
      82             :                              DwarfDebug *DW, DwarfFile *DWU,
      83          36 :                              MCDwarfDwoLineTable *SplitLineTable)
      84             :     : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
      85          36 :       SplitLineTable(SplitLineTable) {
      86          36 :   if (SplitLineTable)
      87          38 :     addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
      88          36 : }
      89             : 
      90        4806 : DwarfUnit::~DwarfUnit() {
      91        1602 :   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
      92             :     DIEBlocks[j]->~DIEBlock();
      93        1602 :   for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
      94             :     DIELocs[j]->~DIELoc();
      95         801 : }
      96             : 
      97         241 : int64_t DwarfUnit::getDefaultLowerBound() const {
      98         482 :   switch (getLanguage()) {
      99             :   default:
     100             :     break;
     101             : 
     102             :   // The languages below have valid values in all DWARF versions.
     103             :   case dwarf::DW_LANG_C:
     104             :   case dwarf::DW_LANG_C89:
     105             :   case dwarf::DW_LANG_C_plus_plus:
     106             :     return 0;
     107             : 
     108           0 :   case dwarf::DW_LANG_Fortran77:
     109             :   case dwarf::DW_LANG_Fortran90:
     110           0 :     return 1;
     111             : 
     112             :   // The languages below have valid values only if the DWARF version >= 3.
     113          63 :   case dwarf::DW_LANG_C99:
     114             :   case dwarf::DW_LANG_ObjC:
     115             :   case dwarf::DW_LANG_ObjC_plus_plus:
     116          63 :     if (DD->getDwarfVersion() >= 3)
     117             :       return 0;
     118             :     break;
     119             : 
     120           0 :   case dwarf::DW_LANG_Fortran95:
     121           0 :     if (DD->getDwarfVersion() >= 3)
     122             :       return 1;
     123             :     break;
     124             : 
     125             :   // Starting with DWARF v4, all defined languages have valid values.
     126           0 :   case dwarf::DW_LANG_D:
     127             :   case dwarf::DW_LANG_Java:
     128             :   case dwarf::DW_LANG_Python:
     129             :   case dwarf::DW_LANG_UPC:
     130           0 :     if (DD->getDwarfVersion() >= 4)
     131             :       return 0;
     132             :     break;
     133             : 
     134           0 :   case dwarf::DW_LANG_Ada83:
     135             :   case dwarf::DW_LANG_Ada95:
     136             :   case dwarf::DW_LANG_Cobol74:
     137             :   case dwarf::DW_LANG_Cobol85:
     138             :   case dwarf::DW_LANG_Modula2:
     139             :   case dwarf::DW_LANG_Pascal83:
     140             :   case dwarf::DW_LANG_PLI:
     141           0 :     if (DD->getDwarfVersion() >= 4)
     142             :       return 1;
     143             :     break;
     144             : 
     145             :   // The languages below are new in DWARF v5.
     146           2 :   case dwarf::DW_LANG_BLISS:
     147             :   case dwarf::DW_LANG_C11:
     148             :   case dwarf::DW_LANG_C_plus_plus_03:
     149             :   case dwarf::DW_LANG_C_plus_plus_11:
     150             :   case dwarf::DW_LANG_C_plus_plus_14:
     151             :   case dwarf::DW_LANG_Dylan:
     152             :   case dwarf::DW_LANG_Go:
     153             :   case dwarf::DW_LANG_Haskell:
     154             :   case dwarf::DW_LANG_OCaml:
     155             :   case dwarf::DW_LANG_OpenCL:
     156             :   case dwarf::DW_LANG_RenderScript:
     157             :   case dwarf::DW_LANG_Rust:
     158             :   case dwarf::DW_LANG_Swift:
     159           2 :     if (DD->getDwarfVersion() >= 5)
     160             :       return 0;
     161             :     break;
     162             : 
     163           0 :   case dwarf::DW_LANG_Fortran03:
     164             :   case dwarf::DW_LANG_Fortran08:
     165             :   case dwarf::DW_LANG_Julia:
     166             :   case dwarf::DW_LANG_Modula3:
     167           0 :     if (DD->getDwarfVersion() >= 5)
     168             :       return 1;
     169             :     break;
     170             :   }
     171             : 
     172             :   return -1;
     173             : }
     174             : 
     175             : /// Check whether the DIE for this MDNode can be shared across CUs.
     176      207992 : bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const {
     177             :   // When the MDNode can be part of the type system, the DIE can be shared
     178             :   // across CUs.
     179             :   // Combining type units and cross-CU DIE sharing is lower value (since
     180             :   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
     181             :   // level already) but may be implementable for some value in projects
     182             :   // building multiple independent libraries with LTO and then linking those
     183             :   // together.
     184      207992 :   if (isDwoUnit() && !DD->shareAcrossDWOCUs())
     185             :     return false;
     186      307538 :   return (isa<DIType>(D) ||
     187      396598 :           (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
     188      143041 :          !GenerateDwarfTypeUnits;
     189             : }
     190             : 
     191      163435 : DIE *DwarfUnit::getDIE(const DINode *D) const {
     192      163435 :   if (isShareableAcrossCUs(D))
     193      224028 :     return DU->getDIE(D);
     194      102842 :   return MDNodeToDieMap.lookup(D);
     195             : }
     196             : 
     197       44557 : void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
     198       44557 :   if (isShareableAcrossCUs(Desc)) {
     199       30889 :     DU->insertDIE(Desc, D);
     200             :     return;
     201             :   }
     202       54672 :   MDNodeToDieMap.insert(std::make_pair(Desc, D));
     203             : }
     204             : 
     205       47418 : void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
     206       47418 :   if (DD->getDwarfVersion() >= 4)
     207       46875 :     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
     208       46875 :                  DIEInteger(1));
     209             :   else
     210         543 :     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
     211         543 :                  DIEInteger(1));
     212       47418 : }
     213             : 
     214      278365 : void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
     215             :                         Optional<dwarf::Form> Form, uint64_t Integer) {
     216      278365 :   if (!Form)
     217      528670 :     Form = DIEInteger::BestForm(false, Integer);
     218             :   assert(Form != dwarf::DW_FORM_implicit_const &&
     219             :          "DW_FORM_implicit_const is used only for signed integers");
     220      835095 :   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
     221      278365 : }
     222             : 
     223        2525 : void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
     224             :                         uint64_t Integer) {
     225        5050 :   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
     226        2525 : }
     227             : 
     228         768 : void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
     229             :                         Optional<dwarf::Form> Form, int64_t Integer) {
     230         768 :   if (!Form)
     231           0 :     Form = DIEInteger::BestForm(true, Integer);
     232        2304 :   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
     233         768 : }
     234             : 
     235         480 : void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
     236             :                         int64_t Integer) {
     237         960 :   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
     238         480 : }
     239             : 
     240       68487 : void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
     241             :                           StringRef String) {
     242       68487 :   Die.addValue(DIEValueAllocator, Attribute,
     243       68487 :                isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
     244      205461 :                DIEString(DU->getStringPool().getEntry(*Asm, String)));
     245       68487 : }
     246             : 
     247       55496 : DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
     248             :                                                  dwarf::Attribute Attribute,
     249             :                                                  dwarf::Form Form,
     250             :                                                  const MCSymbol *Label) {
     251      110992 :   return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
     252             : }
     253             : 
     254         273 : void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
     255         273 :   addLabel(Die, (dwarf::Attribute)0, Form, Label);
     256         273 : }
     257             : 
     258          19 : void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
     259             :                                  uint64_t Integer) {
     260          19 :   if (DD->getDwarfVersion() >= 4)
     261          57 :     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
     262             :   else
     263           0 :     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
     264          19 : }
     265             : 
     266          61 : unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
     267         122 :   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
     268          91 :                         : getCU().getOrCreateSourceID(FileName, DirName);
     269             : }
     270             : 
     271         299 : void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
     272         299 :   if (!DD->useSplitDwarf()) {
     273         273 :     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
     274         273 :     addLabel(Die, dwarf::DW_FORM_udata, Sym);
     275             :   } else {
     276          26 :     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
     277          26 :     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
     278          52 :             DD->getAddressPool().getIndex(Sym));
     279             :   }
     280         299 : }
     281             : 
     282       38746 : void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
     283             :                               const MCSymbol *Hi, const MCSymbol *Lo) {
     284       38746 :   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
     285      116238 :                new (DIEValueAllocator) DIEDelta(Hi, Lo));
     286       38746 : }
     287             : 
     288      106906 : void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
     289      106906 :   addDIEEntry(Die, Attribute, DIEEntry(Entry));
     290      106906 : }
     291             : 
     292          38 : void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
     293             :   // Flag the type unit reference as a declaration so that if it contains
     294             :   // members (implicit special members, static data member definitions, member
     295             :   // declarations for definitions in this CU, etc) consumers don't get confused
     296             :   // and think this is a full definition.
     297          38 :   addFlag(Die, dwarf::DW_AT_declaration);
     298             : 
     299          38 :   Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
     300          38 :                dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
     301          38 : }
     302             : 
     303      176111 : void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
     304             :                             DIEEntry Entry) {
     305      176111 :   const DIEUnit *CU = Die.getUnit();
     306      176111 :   const DIEUnit *EntryCU = Entry.getEntry().getUnit();
     307      176111 :   if (!CU)
     308             :     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
     309      200318 :     CU = getUnitDie().getUnit();
     310      176111 :   if (!EntryCU)
     311           2 :     EntryCU = getUnitDie().getUnit();
     312      176111 :   Die.addValue(DIEValueAllocator, Attribute,
     313             :                EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
     314      176111 :                Entry);
     315      176111 : }
     316             : 
     317       89546 : DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
     318      179092 :   DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
     319       89546 :   if (N)
     320       36880 :     insertDIE(N, &Die);
     321       89546 :   return Die;
     322             : }
     323             : 
     324        2111 : void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
     325        2111 :   Loc->ComputeSize(Asm);
     326        2111 :   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
     327        2111 :   Die.addValue(DIEValueAllocator, Attribute,
     328        4222 :                Loc->BestForm(DD->getDwarfVersion()), Loc);
     329        2111 : }
     330             : 
     331           3 : void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
     332             :                          DIEBlock *Block) {
     333           3 :   Block->ComputeSize(Asm);
     334           3 :   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
     335           9 :   Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
     336           3 : }
     337             : 
     338       49279 : void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
     339             :                               StringRef Directory) {
     340       49279 :   if (Line == 0)
     341             :     return;
     342             : 
     343       39868 :   unsigned FileID = getOrCreateSourceID(File, Directory);
     344             :   assert(FileID && "Invalid file id");
     345      119604 :   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
     346      119604 :   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
     347             : }
     348             : 
     349        8048 : void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
     350             :   assert(V);
     351             : 
     352       16096 :   addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
     353        8048 :                 V->getScope()->getDirectory());
     354        8048 : }
     355             : 
     356         417 : void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
     357             :   assert(G);
     358             : 
     359         417 :   addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
     360         417 : }
     361             : 
     362       17367 : void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
     363             :   assert(SP);
     364             : 
     365       17367 :   addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
     366       17367 : }
     367             : 
     368       16525 : void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
     369             :   assert(Ty);
     370             : 
     371       16525 :   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
     372       16525 : }
     373             : 
     374          10 : void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
     375             :   assert(Ty);
     376             : 
     377          10 :   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
     378          10 : }
     379             : 
     380             : /* Byref variables, in Blocks, are declared by the programmer as "SomeType
     381             :    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
     382             :    gives the variable VarName either the struct, or a pointer to the struct, as
     383             :    its type.  This is necessary for various behind-the-scenes things the
     384             :    compiler needs to do with by-reference variables in Blocks.
     385             : 
     386             :    However, as far as the original *programmer* is concerned, the variable
     387             :    should still have type 'SomeType', as originally declared.
     388             : 
     389             :    The function getBlockByrefType dives into the __Block_byref_x_VarName
     390             :    struct to find the original type of the variable, which is then assigned to
     391             :    the variable's Debug Information Entry as its real type.  So far, so good.
     392             :    However now the debugger will expect the variable VarName to have the type
     393             :    SomeType.  So we need the location attribute for the variable to be an
     394             :    expression that explains to the debugger how to navigate through the
     395             :    pointers and struct to find the actual variable of type SomeType.
     396             : 
     397             :    The following function does just that.  We start by getting
     398             :    the "normal" location for the variable. This will be the location
     399             :    of either the struct __Block_byref_x_VarName or the pointer to the
     400             :    struct __Block_byref_x_VarName.
     401             : 
     402             :    The struct will look something like:
     403             : 
     404             :    struct __Block_byref_x_VarName {
     405             :      ... <various fields>
     406             :      struct __Block_byref_x_VarName *forwarding;
     407             :      ... <various other fields>
     408             :      SomeType VarName;
     409             :      ... <maybe more fields>
     410             :    };
     411             : 
     412             :    If we are given the struct directly (as our starting point) we
     413             :    need to tell the debugger to:
     414             : 
     415             :    1).  Add the offset of the forwarding field.
     416             : 
     417             :    2).  Follow that pointer to get the real __Block_byref_x_VarName
     418             :    struct to use (the real one may have been copied onto the heap).
     419             : 
     420             :    3).  Add the offset for the field VarName, to find the actual variable.
     421             : 
     422             :    If we started with a pointer to the struct, then we need to
     423             :    dereference that pointer first, before the other steps.
     424             :    Translating this into DWARF ops, we will need to append the following
     425             :    to the current location description for the variable:
     426             : 
     427             :    DW_OP_deref                    -- optional, if we start with a pointer
     428             :    DW_OP_plus_uconst <forward_fld_offset>
     429             :    DW_OP_deref
     430             :    DW_OP_plus_uconst <varName_fld_offset>
     431             : 
     432             :    That is what this function does.  */
     433             : 
     434           0 : void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
     435             :                                      dwarf::Attribute Attribute,
     436             :                                      const MachineLocation &Location) {
     437           0 :   const DIType *Ty = DV.getType();
     438           0 :   const DIType *TmpTy = Ty;
     439           0 :   uint16_t Tag = Ty->getTag();
     440           0 :   bool isPointer = false;
     441             : 
     442           0 :   StringRef varName = DV.getName();
     443             : 
     444           0 :   if (Tag == dwarf::DW_TAG_pointer_type) {
     445           0 :     auto *DTy = cast<DIDerivedType>(Ty);
     446           0 :     TmpTy = resolve(DTy->getBaseType());
     447             :     isPointer = true;
     448             :   }
     449             : 
     450             :   // Find the __forwarding field and the variable field in the __Block_byref
     451             :   // struct.
     452           0 :   DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
     453           0 :   const DIDerivedType *varField = nullptr;
     454           0 :   const DIDerivedType *forwardingField = nullptr;
     455             : 
     456           0 :   for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
     457           0 :     auto *DT = cast<DIDerivedType>(Fields[i]);
     458           0 :     StringRef fieldName = DT->getName();
     459           0 :     if (fieldName == "__forwarding")
     460             :       forwardingField = DT;
     461           0 :     else if (fieldName == varName)
     462             :       varField = DT;
     463             :   }
     464             : 
     465             :   // Get the offsets for the forwarding field and the variable field.
     466           0 :   unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
     467           0 :   unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
     468             : 
     469             :   // Decode the original location, and use that as the start of the byref
     470             :   // variable's location.
     471           0 :   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
     472           0 :   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
     473           0 :   if (Location.isIndirect())
     474           0 :     DwarfExpr.setMemoryLocationKind();
     475             : 
     476           0 :   SmallVector<uint64_t, 6> Ops;
     477             :   // If we started with a pointer to the __Block_byref... struct, then
     478             :   // the first thing we need to do is dereference the pointer (DW_OP_deref).
     479           0 :   if (isPointer)
     480           0 :     Ops.push_back(dwarf::DW_OP_deref);
     481             : 
     482             :   // Next add the offset for the '__forwarding' field:
     483             :   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
     484             :   // adding the offset if it's 0.
     485           0 :   if (forwardingFieldOffset > 0) {
     486           0 :     Ops.push_back(dwarf::DW_OP_plus_uconst);
     487           0 :     Ops.push_back(forwardingFieldOffset);
     488             :   }
     489             : 
     490             :   // Now dereference the __forwarding field to get to the real __Block_byref
     491             :   // struct:  DW_OP_deref.
     492           0 :   Ops.push_back(dwarf::DW_OP_deref);
     493             : 
     494             :   // Now that we've got the real __Block_byref... struct, add the offset
     495             :   // for the variable's field to get to the location of the actual variable:
     496             :   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
     497           0 :   if (varFieldOffset > 0) {
     498           0 :     Ops.push_back(dwarf::DW_OP_plus_uconst);
     499           0 :     Ops.push_back(varFieldOffset);
     500             :   }
     501             : 
     502           0 :   DIExpressionCursor Cursor(Ops);
     503           0 :   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
     504           0 :   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
     505           0 :     return;
     506           0 :   DwarfExpr.addExpression(std::move(Cursor));
     507             : 
     508             :   // Now attach the location information to the DIE.
     509           0 :   addBlock(Die, Attribute, DwarfExpr.finalize());
     510             : }
     511             : 
     512             : /// Return true if type encoding is unsigned.
     513        1521 : static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
     514          77 :   if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
     515             :     // FIXME: Enums without a fixed underlying type have unknown signedness
     516             :     // here, leading to incorrectly emitted constants.
     517          77 :     if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
     518             :       return false;
     519             : 
     520             :     // (Pieces of) aggregate types that get hacked apart by SROA may be
     521             :     // represented by a constant. Encode them as unsigned bytes.
     522          13 :     return true;
     523             :   }
     524             : 
     525        1667 :   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
     526        1667 :     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
     527             :     // Encode pointer constants as unsigned bytes. This is used at least for
     528             :     // null pointer constant emission.
     529             :     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
     530             :     // here, but accept them for now due to a bug in SROA producing bogus
     531             :     // dbg.values.
     532        3334 :     if (T == dwarf::DW_TAG_pointer_type ||
     533        1667 :         T == dwarf::DW_TAG_ptr_to_member_type ||
     534        3330 :         T == dwarf::DW_TAG_reference_type ||
     535        1665 :         T == dwarf::DW_TAG_rvalue_reference_type)
     536             :       return true;
     537             :     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
     538             :            T == dwarf::DW_TAG_volatile_type ||
     539             :            T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
     540        1665 :     DITypeRef Deriv = DTy->getBaseType();
     541             :     assert(Deriv && "Expected valid base type");
     542        3330 :     return isUnsignedDIType(DD, DD->resolve(Deriv));
     543             :   }
     544             : 
     545        1442 :   auto *BTy = cast<DIBasicType>(Ty);
     546        1442 :   unsigned Encoding = BTy->getEncoding();
     547             :   assert((Encoding == dwarf::DW_ATE_unsigned ||
     548             :           Encoding == dwarf::DW_ATE_unsigned_char ||
     549             :           Encoding == dwarf::DW_ATE_signed ||
     550             :           Encoding == dwarf::DW_ATE_signed_char ||
     551             :           Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
     552             :           Encoding == dwarf::DW_ATE_boolean ||
     553             :           (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
     554             :            Ty->getName() == "decltype(nullptr)")) &&
     555             :          "Unsupported encoding");
     556        1442 :   return Encoding == dwarf::DW_ATE_unsigned ||
     557        1442 :          Encoding == dwarf::DW_ATE_unsigned_char ||
     558        3030 :          Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
     559         146 :          Ty->getTag() == dwarf::DW_TAG_unspecified_type;
     560             : }
     561             : 
     562           2 : void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
     563             :   assert(MO.isFPImm() && "Invalid machine operand!");
     564           6 :   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
     565           6 :   APFloat FPImm = MO.getFPImm()->getValueAPF();
     566             : 
     567             :   // Get the raw data form of the floating point.
     568           4 :   const APInt FltVal = FPImm.bitcastToAPInt();
     569           2 :   const char *FltPtr = (const char *)FltVal.getRawData();
     570             : 
     571           2 :   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
     572           4 :   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
     573           2 :   int Incr = (LittleEndian ? 1 : -1);
     574           2 :   int Start = (LittleEndian ? 0 : NumBytes - 1);
     575           2 :   int Stop = (LittleEndian ? NumBytes : -1);
     576             : 
     577             :   // Output the constant to DWARF one byte at a time.
     578          42 :   for (; Start != Stop; Start += Incr)
     579          20 :     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
     580             : 
     581           2 :   addBlock(Die, dwarf::DW_AT_const_value, Block);
     582           2 : }
     583             : 
     584           2 : void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
     585             :   // Pass this down to addConstantValue as an unsigned bag of bits.
     586           4 :   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
     587           2 : }
     588             : 
     589         760 : void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
     590             :                                  const DIType *Ty) {
     591         760 :   addConstantValue(Die, CI->getValue(), Ty);
     592         760 : }
     593             : 
     594         761 : void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
     595             :                                  const DIType *Ty) {
     596             :   assert(MO.isImm() && "Invalid machine operand!");
     597             : 
     598         761 :   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
     599         761 : }
     600             : 
     601        1527 : void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
     602             :   // FIXME: This is a bit conservative/simple - it emits negative values always
     603             :   // sign extended to 64 bits rather than minimizing the number of bytes.
     604        3054 :   addUInt(Die, dwarf::DW_AT_const_value,
     605        1527 :           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
     606        1527 : }
     607             : 
     608         760 : void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
     609         760 :   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
     610         760 : }
     611             : 
     612         762 : void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
     613         762 :   unsigned CIBitWidth = Val.getBitWidth();
     614         762 :   if (CIBitWidth <= 64) {
     615        1522 :     addConstantValue(Die, Unsigned,
     616          68 :                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
     617         761 :     return;
     618             :   }
     619             : 
     620           3 :   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
     621             : 
     622             :   // Get the raw data form of the large APInt.
     623           1 :   const uint64_t *Ptr64 = Val.getRawData();
     624             : 
     625           1 :   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
     626           1 :   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
     627             : 
     628             :   // Output the constant to DWARF one byte at a time.
     629          17 :   for (int i = 0; i < NumBytes; i++) {
     630             :     uint8_t c;
     631          16 :     if (LittleEndian)
     632          16 :       c = Ptr64[i / 8] >> (8 * (i & 7));
     633             :     else
     634           0 :       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
     635          16 :     addUInt(*Block, dwarf::DW_FORM_data1, c);
     636             :   }
     637             : 
     638           1 :   addBlock(Die, dwarf::DW_AT_const_value, Block);
     639             : }
     640             : 
     641       18231 : void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
     642       18231 :   if (!LinkageName.empty())
     643       19674 :     addString(Die,
     644        9837 :               DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
     645             :                                          : dwarf::DW_AT_MIPS_linkage_name,
     646             :               GlobalValue::dropLLVMManglingEscape(LinkageName));
     647       18231 : }
     648             : 
     649       21967 : void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
     650             :   // Add template parameters.
     651       70673 :   for (const auto *Element : TParams) {
     652        3934 :     if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
     653        3934 :       constructTemplateTypeParameterDIE(Buffer, TTP);
     654         838 :     else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
     655         838 :       constructTemplateValueParameterDIE(Buffer, TVP);
     656             :   }
     657       21967 : }
     658             : 
     659             : /// Add thrown types.
     660       17366 : void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
     661       52100 :   for (const auto *Ty : ThrownTypes) {
     662           2 :     DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
     663           2 :     addType(TT, cast<DIType>(Ty));
     664             :   }
     665       17366 : }
     666             : 
     667      159545 : DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
     668      227694 :   if (!Context || isa<DIFile>(Context))
     669      196066 :     return &getUnitDie();
     670      123024 :   if (auto *T = dyn_cast<DIType>(Context))
     671       21133 :     return getOrCreateTypeDIE(T);
     672       80758 :   if (auto *NS = dyn_cast<DINamespace>(Context))
     673       39599 :     return getOrCreateNameSpace(NS);
     674        1560 :   if (auto *SP = dyn_cast<DISubprogram>(Context))
     675         264 :     return getOrCreateSubprogramDIE(SP);
     676        1032 :   if (auto *M = dyn_cast<DIModule>(Context))
     677         227 :     return getOrCreateModule(M);
     678         289 :   return getDIE(Context);
     679             : }
     680             : 
     681          36 : DIE *DwarfTypeUnit::createTypeDIE(const DICompositeType *Ty) {
     682         108 :   auto *Context = resolve(Ty->getScope());
     683          36 :   DIE *ContextDIE = getOrCreateContextDIE(Context);
     684             : 
     685          36 :   if (DIE *TyDIE = getDIE(Ty))
     686             :     return TyDIE;
     687             : 
     688             :   // Create new type.
     689          72 :   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
     690             : 
     691          72 :   constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
     692             : 
     693          36 :   updateAcceleratorTables(Context, Ty, TyDIE);
     694          36 :   return &TyDIE;
     695             : }
     696             : 
     697       92259 : DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
     698       92261 :   if (!TyNode)
     699             :     return nullptr;
     700             : 
     701       92261 :   auto *Ty = cast<DIType>(TyNode);
     702             : 
     703             :   // DW_TAG_restrict_type is not supported in DWARF2
     704       92261 :   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
     705           3 :     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
     706             : 
     707             :   // DW_TAG_atomic_type is not supported in DWARF < 5
     708       92262 :   if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
     709           3 :     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
     710             : 
     711             :   // Construct the context before querying for the existence of the DIE in case
     712             :   // such construction creates the DIE.
     713      184518 :   auto *Context = resolve(Ty->getScope());
     714       92259 :   DIE *ContextDIE = getOrCreateContextDIE(Context);
     715             :   assert(ContextDIE);
     716             : 
     717       92259 :   if (DIE *TyDIE = getDIE(Ty))
     718             :     return TyDIE;
     719             : 
     720             :   // Create new type.
     721       29720 :   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
     722             : 
     723       14860 :   updateAcceleratorTables(Context, Ty, TyDIE);
     724             : 
     725       14860 :   if (auto *BT = dyn_cast<DIBasicType>(Ty))
     726        1019 :     constructTypeDIE(TyDIE, BT);
     727       13841 :   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
     728         119 :     constructTypeDIE(TyDIE, STy);
     729       13722 :   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
     730        2768 :     if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
     731          46 :       if (MDString *TypeId = CTy->getRawIdentifier()) {
     732          46 :         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
     733             :         // Skip updating the accelerator tables since this is not the full type.
     734          46 :         return &TyDIE;
     735             :       }
     736        2671 :     constructTypeDIE(TyDIE, CTy);
     737             :   } else {
     738       11005 :     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
     739             :   }
     740             : 
     741             :   return &TyDIE;
     742             : }
     743             : 
     744       14896 : void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
     745             :                                         const DIType *Ty, const DIE &TyDIE) {
     746       22170 :   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
     747        6858 :     bool IsImplementation = false;
     748        1787 :     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
     749             :       // A runtime language of 0 actually means C/C++ and that any
     750             :       // non-negative value is some version of Objective-C/C++.
     751        1833 :       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
     752             :     }
     753        6858 :     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
     754       13716 :     DD->addAccelType(Ty->getName(), TyDIE, Flags);
     755             : 
     756       19276 :     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
     757        4080 :         isa<DINamespace>(Context))
     758        4159 :       addGlobalType(Ty, TyDIE, Context);
     759             :   }
     760       14896 : }
     761             : 
     762       69205 : void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
     763             :                         dwarf::Attribute Attribute) {
     764             :   assert(Ty && "Trying to add a type that doesn't exist?");
     765      138410 :   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
     766       69205 : }
     767             : 
     768        7392 : std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
     769        7392 :   if (!Context)
     770        5330 :     return "";
     771             : 
     772             :   // FIXME: Decide whether to implement this for non-C++ languages.
     773        9454 :   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
     774         676 :     return "";
     775             : 
     776        4389 :   std::string CS;
     777        4389 :   SmallVector<const DIScope *, 1> Parents;
     778       16518 :   while (!isa<DICompileUnit>(Context)) {
     779        6945 :     Parents.push_back(Context);
     780       13890 :     if (Context->getScope())
     781        5160 :       Context = resolve(Context->getScope());
     782             :     else
     783             :       // Structure, etc types will have a NULL context if they're at the top
     784             :       // level.
     785             :       break;
     786             :   }
     787             : 
     788             :   // Reverse iterate over our list to go from the outermost construct to the
     789             :   // innermost.
     790       40224 :   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
     791        6945 :     StringRef Name = Ctx->getName();
     792        7213 :     if (Name.empty() && isa<DINamespace>(Ctx))
     793             :       Name = "(anonymous namespace)";
     794        6945 :     if (!Name.empty()) {
     795        6702 :       CS += Name;
     796             :       CS += "::";
     797             :     }
     798             :   }
     799        4389 :   return CS;
     800             : }
     801             : 
     802        1019 : void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
     803             :   // Get core information.
     804        2038 :   StringRef Name = BTy->getName();
     805             :   // Add name if not anonymous or intermediate type.
     806        1019 :   if (!Name.empty())
     807        1011 :     addString(Buffer, dwarf::DW_AT_name, Name);
     808             : 
     809             :   // An unspecified type only has a name attribute.
     810        1019 :   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
     811          25 :     return;
     812             : 
     813        2982 :   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
     814         994 :           BTy->getEncoding());
     815             : 
     816         994 :   uint64_t Size = BTy->getSizeInBits() >> 3;
     817        1988 :   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
     818             : }
     819             : 
     820       11005 : void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
     821             :   // Get core information.
     822       22010 :   StringRef Name = DTy->getName();
     823       11005 :   uint64_t Size = DTy->getSizeInBits() >> 3;
     824       11005 :   uint16_t Tag = Buffer.getTag();
     825             : 
     826             :   // Map to main type, void will not have a type.
     827       21905 :   const DIType *FromTy = resolve(DTy->getBaseType());
     828             :   if (FromTy)
     829       10900 :     addType(Buffer, FromTy);
     830             : 
     831             :   // Add name if not anonymous or intermediate type.
     832       11005 :   if (!Name.empty())
     833        4060 :     addString(Buffer, dwarf::DW_AT_name, Name);
     834             : 
     835             :   // Add size if non-zero (derived types might be zero-sized.)
     836       11005 :   if (Size && Tag != dwarf::DW_TAG_pointer_type
     837        2018 :            && Tag != dwarf::DW_TAG_ptr_to_member_type
     838        2018 :            && Tag != dwarf::DW_TAG_reference_type
     839         341 :            && Tag != dwarf::DW_TAG_rvalue_reference_type)
     840           6 :     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
     841             : 
     842       11005 :   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
     843          10 :     addDIEEntry(
     844             :         Buffer, dwarf::DW_AT_containing_type,
     845          30 :         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
     846             :   // Add source line info if available and TyDesc is not a forward declaration.
     847       22010 :   if (!DTy->isForwardDecl())
     848       11005 :     addSourceLine(Buffer, DTy);
     849             : 
     850             :   // If DWARF address space value is other than None, add it for pointer and
     851             :   // reference types as DW_AT_address_class.
     852       33015 :   if (DTy->getDWARFAddressSpace() && (Tag == dwarf::DW_TAG_pointer_type ||
     853       11005 :                                       Tag == dwarf::DW_TAG_reference_type))
     854           6 :     addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
     855           6 :             DTy->getDWARFAddressSpace().getValue());
     856       11005 : }
     857             : 
     858       16058 : void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
     859       61968 :   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
     860       59704 :     const DIType *Ty = resolve(Args[i]);
     861             :     if (!Ty) {
     862             :       assert(i == N-1 && "Unspecified parameter must be the last argument");
     863         317 :       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
     864             :     } else {
     865       29535 :       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
     866       29535 :       addType(Arg, Ty);
     867       29535 :       if (Ty->isArtificial())
     868        9503 :         addFlag(Arg, dwarf::DW_AT_artificial);
     869             :     }
     870             :   }
     871       16058 : }
     872             : 
     873         119 : void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
     874             :   // Add return type.  A void return won't have a type.
     875         238 :   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
     876         119 :   if (Elements.size())
     877         185 :     if (auto RTy = resolve(Elements[0]))
     878          66 :       addType(Buffer, RTy);
     879             : 
     880         119 :   bool isPrototyped = true;
     881         136 :   if (Elements.size() == 2 && !Elements[1])
     882             :     isPrototyped = false;
     883             : 
     884         119 :   constructSubprogramArguments(Buffer, Elements);
     885             : 
     886             :   // Add prototype flag if we're dealing with a C language and the function has
     887             :   // been prototyped.
     888         238 :   uint16_t Language = getLanguage();
     889         237 :   if (isPrototyped &&
     890         234 :       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
     891             :        Language == dwarf::DW_LANG_ObjC))
     892           5 :     addFlag(Buffer, dwarf::DW_AT_prototyped);
     893             : 
     894             :   // Add a DW_AT_calling_convention if this has an explicit convention.
     895         119 :   if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
     896           3 :     addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
     897           1 :             CTy->getCC());
     898             : 
     899         238 :   if (CTy->isLValueReference())
     900           1 :     addFlag(Buffer, dwarf::DW_AT_reference);
     901             : 
     902         238 :   if (CTy->isRValueReference())
     903           1 :     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
     904         119 : }
     905             : 
     906        2714 : void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
     907             :   // Add name if not anonymous or intermediate type.
     908        5428 :   StringRef Name = CTy->getName();
     909             : 
     910        2714 :   uint64_t Size = CTy->getSizeInBits() >> 3;
     911        2714 :   uint16_t Tag = Buffer.getTag();
     912             : 
     913        2714 :   switch (Tag) {
     914         221 :   case dwarf::DW_TAG_array_type:
     915         221 :     constructArrayTypeDIE(Buffer, CTy);
     916         221 :     break;
     917         101 :   case dwarf::DW_TAG_enumeration_type:
     918         101 :     constructEnumTypeDIE(Buffer, CTy);
     919         101 :     break;
     920        2392 :   case dwarf::DW_TAG_structure_type:
     921             :   case dwarf::DW_TAG_union_type:
     922             :   case dwarf::DW_TAG_class_type: {
     923             :     // Add elements to structure type.
     924        2392 :     DINodeArray Elements = CTy->getElements();
     925       20730 :     for (const auto *Element : Elements) {
     926           0 :       if (!Element)
     927           0 :         continue;
     928       13554 :       if (auto *SP = dyn_cast<DISubprogram>(Element))
     929       10025 :         getOrCreateSubprogramDIE(SP);
     930        3529 :       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
     931        3519 :         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
     932           1 :           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
     933           2 :           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
     934        7036 :         } else if (DDTy->isStaticMember()) {
     935         230 :           getOrCreateStaticMemberDIE(DDTy);
     936             :         } else {
     937        3288 :           constructMemberDIE(Buffer, DDTy);
     938             :         }
     939          10 :       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
     940          20 :         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
     941          10 :         StringRef PropertyName = Property->getName();
     942          10 :         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
     943          10 :         if (Property->getType())
     944          18 :           addType(ElemDie, resolve(Property->getType()));
     945          10 :         addSourceLine(ElemDie, Property);
     946          10 :         StringRef GetterName = Property->getGetterName();
     947          10 :         if (!GetterName.empty())
     948           1 :           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
     949          10 :         StringRef SetterName = Property->getSetterName();
     950          10 :         if (!SetterName.empty())
     951           1 :           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
     952          10 :         if (unsigned PropertyAttributes = Property->getAttributes())
     953          30 :           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
     954             :                   PropertyAttributes);
     955             :       }
     956             :     }
     957             : 
     958        4784 :     if (CTy->isAppleBlockExtension())
     959           8 :       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
     960             : 
     961             :     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
     962             :     // inside C++ composite types to point to the base class with the vtable.
     963             :     if (auto *ContainingType =
     964        2436 :             dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
     965          22 :       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
     966          22 :                   *getOrCreateTypeDIE(ContainingType));
     967             : 
     968        4784 :     if (CTy->isObjcClassComplete())
     969          19 :       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
     970             : 
     971             :     // Add template parameters to a class, structure or union types.
     972             :     // FIXME: The support isn't in the metadata for this yet.
     973        4784 :     if (Tag == dwarf::DW_TAG_class_type ||
     974        2454 :         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
     975        4784 :       addTemplateParams(Buffer, CTy->getTemplateParams());
     976             : 
     977             :     break;
     978             :   }
     979             :   default:
     980             :     break;
     981             :   }
     982             : 
     983             :   // Add name if not anonymous or intermediate type.
     984        2714 :   if (!Name.empty())
     985        2168 :     addString(Buffer, dwarf::DW_AT_name, Name);
     986             : 
     987        5428 :   if (Tag == dwarf::DW_TAG_enumeration_type ||
     988        6546 :       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
     989        1916 :       Tag == dwarf::DW_TAG_union_type) {
     990             :     // Add size if non-zero (derived types might be zero-sized.)
     991             :     // TODO: Do we care about size for enum forward declarations?
     992        2493 :     if (Size)
     993        3928 :       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
     994        1058 :     else if (!CTy->isForwardDecl())
     995             :       // Add zero size if it is not a forward declaration.
     996          78 :       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
     997             : 
     998             :     // If we're a forward decl, say so.
     999        4986 :     if (CTy->isForwardDecl())
    1000         491 :       addFlag(Buffer, dwarf::DW_AT_declaration);
    1001             : 
    1002             :     // Add source line info if available.
    1003        4986 :     if (!CTy->isForwardDecl())
    1004        2002 :       addSourceLine(Buffer, CTy);
    1005             : 
    1006             :     // No harm in adding the runtime language to the declaration.
    1007        2493 :     unsigned RLang = CTy->getRuntimeLang();
    1008        2493 :     if (RLang)
    1009         156 :       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
    1010             :               RLang);
    1011             : 
    1012             :     // Add align info if available.
    1013        4986 :     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
    1014         744 :       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
    1015             :               AlignInBytes);
    1016             :   }
    1017        2714 : }
    1018             : 
    1019        3934 : void DwarfUnit::constructTemplateTypeParameterDIE(
    1020             :     DIE &Buffer, const DITemplateTypeParameter *TP) {
    1021             :   DIE &ParamDIE =
    1022        3934 :       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
    1023             :   // Add the type if it exists, it could be void and therefore no type.
    1024        7868 :   if (TP->getType())
    1025       11604 :     addType(ParamDIE, resolve(TP->getType()));
    1026        7868 :   if (!TP->getName().empty())
    1027        7036 :     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
    1028        3934 : }
    1029             : 
    1030         838 : void DwarfUnit::constructTemplateValueParameterDIE(
    1031             :     DIE &Buffer, const DITemplateValueParameter *VP) {
    1032        1676 :   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
    1033             : 
    1034             :   // Add the type if there is one, template template and template parameter
    1035             :   // packs will not have a type.
    1036         838 :   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
    1037        1752 :     addType(ParamDIE, resolve(VP->getType()));
    1038        1676 :   if (!VP->getName().empty())
    1039        1418 :     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
    1040         838 :   if (Metadata *Val = VP->getValue()) {
    1041        1394 :     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
    1042        1671 :       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
    1043         306 :     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
    1044             :       // We cannot describe the location of dllimport'd entities: the
    1045             :       // computation of their address requires loads from the IAT.
    1046          26 :       if (!GV->hasDLLImportStorageClass()) {
    1047             :         // For declaration non-type template parameters (such as global values
    1048             :         // and functions)
    1049          78 :         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
    1050          26 :         addOpAddress(*Loc, Asm->getSymbol(GV));
    1051             :         // Emit DW_OP_stack_value to use the address as the immediate value of
    1052             :         // the parameter, rather than a pointer to it.
    1053          26 :         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
    1054          26 :         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
    1055             :       }
    1056         508 :     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
    1057             :       assert(isa<MDString>(Val));
    1058           2 :       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
    1059             :                 cast<MDString>(Val)->getString());
    1060         253 :     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
    1061         759 :       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
    1062             :     }
    1063             :   }
    1064         838 : }
    1065             : 
    1066       39642 : DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
    1067             :   // Construct the context before querying for the existence of the DIE in case
    1068             :   // such construction creates the DIE.
    1069       39642 :   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
    1070             : 
    1071       39642 :   if (DIE *NDie = getDIE(NS))
    1072             :     return NDie;
    1073         224 :   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
    1074             : 
    1075         224 :   StringRef Name = NS->getName();
    1076         224 :   if (!Name.empty())
    1077         213 :     addString(NDie, dwarf::DW_AT_name, NS->getName());
    1078             :   else
    1079          11 :     Name = "(anonymous namespace)";
    1080         224 :   DD->addAccelNamespace(Name, NDie);
    1081         448 :   addGlobalName(Name, NDie, NS->getScope());
    1082         224 :   if (NS->getExportSymbols())
    1083          18 :     addFlag(NDie, dwarf::DW_AT_export_symbols);
    1084             :   return &NDie;
    1085             : }
    1086             : 
    1087         230 : DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
    1088             :   // Construct the context before querying for the existence of the DIE in case
    1089             :   // such construction creates the DIE.
    1090         230 :   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
    1091             : 
    1092         230 :   if (DIE *MDie = getDIE(M))
    1093             :     return MDie;
    1094          26 :   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
    1095             : 
    1096          26 :   if (!M->getName().empty()) {
    1097          26 :     addString(MDie, dwarf::DW_AT_name, M->getName());
    1098          78 :     addGlobalName(M->getName(), MDie, M->getScope());
    1099             :   }
    1100          26 :   if (!M->getConfigurationMacros().empty())
    1101           7 :     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
    1102             :               M->getConfigurationMacros());
    1103          26 :   if (!M->getIncludePath().empty())
    1104          21 :     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
    1105          26 :   if (!M->getISysRoot().empty())
    1106          26 :     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
    1107             :   
    1108             :   return &MDie;
    1109             : }
    1110             : 
    1111       23165 : DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
    1112             :   // Construct the context before querying for the existence of the DIE in case
    1113             :   // such construction creates the DIE (as is the case for member function
    1114             :   // declarations).
    1115             :   DIE *ContextDIE =
    1116       65459 :       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
    1117             : 
    1118       23165 :   if (DIE *SPDie = getDIE(SP))
    1119             :     return SPDie;
    1120             : 
    1121         274 :   if (auto *SPDecl = SP->getDeclaration()) {
    1122         274 :     if (!Minimal) {
    1123             :       // Add subprogram definitions to the CU die directly.
    1124         546 :       ContextDIE = &getUnitDie();
    1125             :       // Build the decl now to ensure it precedes the definition.
    1126         273 :       getOrCreateSubprogramDIE(SPDecl);
    1127             :     }
    1128             :   }
    1129             : 
    1130             :   // DW_TAG_inlined_subroutine may refer to this DIE.
    1131       21068 :   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
    1132             : 
    1133             :   // Stop here and fill this in later, depending on whether or not this
    1134             :   // subprogram turns out to have inlined instances or not.
    1135       21068 :   if (SP->isDefinition())
    1136             :     return &SPDie;
    1137             : 
    1138       15939 :   applySubprogramAttributes(SP, SPDie);
    1139       15939 :   return &SPDie;
    1140             : }
    1141             : 
    1142       19322 : bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
    1143             :                                                     DIE &SPDie) {
    1144       19322 :   DIE *DeclDie = nullptr;
    1145       19322 :   StringRef DeclLinkageName;
    1146        1955 :   if (auto *SPDecl = SP->getDeclaration()) {
    1147        1955 :     DeclDie = getDIE(SPDecl);
    1148             :     assert(DeclDie && "This DIE should've already been constructed when the "
    1149             :                       "definition DIE was created in "
    1150             :                       "getOrCreateSubprogramDIE");
    1151             :     // Look at the Decl's linkage name only if we emitted it.
    1152        1955 :     if (DD->useAllLinkageNames())
    1153        1951 :       DeclLinkageName = SPDecl->getLinkageName();
    1154             :     unsigned DeclID =
    1155        1955 :         getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
    1156        1955 :     unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
    1157        1955 :     if (DeclID != DefID)
    1158         693 :       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
    1159             : 
    1160        1955 :     if (SP->getLine() != SPDecl->getLine())
    1161        1014 :       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
    1162             :   }
    1163             : 
    1164             :   // Add function template parameters.
    1165       38644 :   addTemplateParams(SPDie, SP->getTemplateParams());
    1166             : 
    1167             :   // Add the linkage name if we have one and it isn't in the Decl.
    1168       19322 :   StringRef LinkageName = SP->getLinkageName();
    1169             :   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
    1170             :           LinkageName == DeclLinkageName) &&
    1171             :          "decl has a linkage name and it is different");
    1172       37141 :   if (DeclLinkageName.empty() &&
    1173             :       // Always emit it for abstract subprograms.
    1174       17876 :       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
    1175       17804 :     addLinkageName(SPDie, LinkageName);
    1176             : 
    1177       19322 :   if (!DeclDie)
    1178             :     return false;
    1179             : 
    1180             :   // Refer to the function declaration where all the other attributes will be
    1181             :   // found.
    1182        1955 :   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
    1183        1955 :   return true;
    1184             : }
    1185             : 
    1186       34984 : void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
    1187             :                                           bool SkipSPAttributes) {
    1188             :   // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
    1189             :   // and its source location.
    1190       50647 :   bool SkipSPSourceLocation = SkipSPAttributes &&
    1191       34985 :                               !CUNode->getDebugInfoForProfiling();
    1192             :   if (!SkipSPSourceLocation)
    1193       19322 :     if (applySubprogramDefinitionAttributes(SP, SPDie))
    1194             :       return;
    1195             : 
    1196             :   // Constructors and operators for anonymous aggregates do not have names.
    1197       33029 :   if (!SP->getName().empty())
    1198       32967 :     addString(SPDie, dwarf::DW_AT_name, SP->getName());
    1199             : 
    1200       33029 :   if (!SkipSPSourceLocation)
    1201       17367 :     addSourceLine(SPDie, SP);
    1202             : 
    1203             :   // Skip the rest of the attributes under -gmlt to save space.
    1204       33029 :   if (SkipSPAttributes)
    1205             :     return;
    1206             : 
    1207             :   // Add the prototype if we have a prototype and we have a C like
    1208             :   // language.
    1209       34732 :   uint16_t Language = getLanguage();
    1210       34539 :   if (SP->isPrototyped() &&
    1211       34130 :       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
    1212             :        Language == dwarf::DW_LANG_ObjC))
    1213         257 :     addFlag(SPDie, dwarf::DW_AT_prototyped);
    1214             : 
    1215       17366 :   unsigned CC = 0;
    1216       17366 :   DITypeRefArray Args;
    1217       17366 :   if (const DISubroutineType *SPTy = SP->getType()) {
    1218       17366 :     Args = SPTy->getTypeArray();
    1219       17366 :     CC = SPTy->getCC();
    1220             :   }
    1221             : 
    1222             :   // Add a DW_AT_calling_convention if this has an explicit convention.
    1223       17366 :   if (CC && CC != dwarf::DW_CC_normal)
    1224           3 :     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
    1225             : 
    1226             :   // Add a return type. If this is a type like a C/C++ void type we don't add a
    1227             :   // return type.
    1228       17366 :   if (Args.size())
    1229       29365 :     if (auto Ty = resolve(Args[0]))
    1230       12033 :       addType(SPDie, Ty);
    1231             : 
    1232       17366 :   unsigned VK = SP->getVirtuality();
    1233       17366 :   if (VK) {
    1234         138 :     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
    1235          46 :     if (SP->getVirtualIndex() != -1u) {
    1236          45 :       DIELoc *Block = getDIELoc();
    1237          45 :       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
    1238          45 :       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
    1239          45 :       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
    1240             :     }
    1241          46 :     ContainingTypeMap.insert(
    1242         276 :         std::make_pair(&SPDie, resolve(SP->getContainingType())));
    1243             :   }
    1244             : 
    1245       17366 :   if (!SP->isDefinition()) {
    1246       15939 :     addFlag(SPDie, dwarf::DW_AT_declaration);
    1247             : 
    1248             :     // Add arguments. Do not add arguments for subprogram definition. They will
    1249             :     // be handled while processing variables.
    1250       15939 :     constructSubprogramArguments(SPDie, Args);
    1251             :   }
    1252             : 
    1253       34732 :   addThrownTypes(SPDie, SP->getThrownTypes());
    1254             : 
    1255       17366 :   if (SP->isArtificial())
    1256          89 :     addFlag(SPDie, dwarf::DW_AT_artificial);
    1257             : 
    1258       17366 :   if (!SP->isLocalToUnit())
    1259       17212 :     addFlag(SPDie, dwarf::DW_AT_external);
    1260             : 
    1261       17366 :   if (DD->useAppleExtensionAttributes()) {
    1262         287 :     if (SP->isOptimized())
    1263         136 :       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
    1264             : 
    1265         287 :     if (unsigned isa = Asm->getISAEncoding())
    1266         147 :       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
    1267             :   }
    1268             : 
    1269       17366 :   if (SP->isLValueReference())
    1270           1 :     addFlag(SPDie, dwarf::DW_AT_reference);
    1271             : 
    1272       17366 :   if (SP->isRValueReference())
    1273           1 :     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
    1274             : 
    1275       17366 :   if (SP->isNoReturn())
    1276         123 :     addFlag(SPDie, dwarf::DW_AT_noreturn);
    1277             : 
    1278       17366 :   if (SP->isProtected())
    1279        2460 :     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1280             :             dwarf::DW_ACCESS_protected);
    1281       16546 :   else if (SP->isPrivate())
    1282         141 :     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1283             :             dwarf::DW_ACCESS_private);
    1284       16499 :   else if (SP->isPublic())
    1285       17904 :     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1286             :             dwarf::DW_ACCESS_public);
    1287             : 
    1288       17366 :   if (SP->isExplicit())
    1289         304 :     addFlag(SPDie, dwarf::DW_AT_explicit);
    1290             : 
    1291       17366 :   if (SP->isMainSubprogram())
    1292           1 :     addFlag(SPDie, dwarf::DW_AT_main_subprogram);
    1293             : }
    1294             : 
    1295         241 : void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
    1296             :                                      DIE *IndexTy) {
    1297         241 :   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
    1298         241 :   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
    1299             : 
    1300             :   // The LowerBound value defines the lower bounds which is typically zero for
    1301             :   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
    1302             :   // Count == -1 then the array is unbounded and we do not emit
    1303             :   // DW_AT_lower_bound and DW_AT_count attributes.
    1304         241 :   int64_t LowerBound = SR->getLowerBound();
    1305         241 :   int64_t DefaultLowerBound = getDefaultLowerBound();
    1306         241 :   int64_t Count = SR->getCount();
    1307             : 
    1308         241 :   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
    1309          21 :     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
    1310             : 
    1311         241 :   if (Count != -1)
    1312             :     // FIXME: An unbounded array should reference the expression that defines
    1313             :     // the array.
    1314         699 :     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
    1315         241 : }
    1316             : 
    1317         221 : DIE *DwarfUnit::getIndexTyDie() {
    1318         221 :   if (IndexTyDie)
    1319             :     return IndexTyDie;
    1320             :   // Construct an integer type to use for indexes.
    1321         128 :   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
    1322          64 :   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
    1323         128 :   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
    1324         192 :   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
    1325             :           dwarf::DW_ATE_unsigned);
    1326          64 :   return IndexTyDie;
    1327             : }
    1328             : 
    1329         221 : void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
    1330         442 :   if (CTy->isVector())
    1331           5 :     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
    1332             : 
    1333             :   // Emit the element type.
    1334         442 :   addType(Buffer, resolve(CTy->getBaseType()));
    1335             : 
    1336             :   // Get an anonymous type for index type.
    1337             :   // FIXME: This type should be passed down from the front end
    1338             :   // as different languages may have different sizes for indexes.
    1339         221 :   DIE *IdxTy = getIndexTyDie();
    1340             : 
    1341             :   // Add subranges to array type.
    1342         221 :   DINodeArray Elements = CTy->getElements();
    1343         683 :   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
    1344             :     // FIXME: Should this really be such a loose cast?
    1345         241 :     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
    1346         241 :       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
    1347         241 :         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
    1348             :   }
    1349         221 : }
    1350             : 
    1351         101 : void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
    1352         101 :   DINodeArray Elements = CTy->getElements();
    1353             : 
    1354             :   // Add enumerators to enumeration type.
    1355         490 :   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
    1356         576 :     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
    1357         288 :     if (Enum) {
    1358         288 :       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
    1359         288 :       StringRef Name = Enum->getName();
    1360         288 :       addString(Enumerator, dwarf::DW_AT_name, Name);
    1361         288 :       int64_t Value = Enum->getValue();
    1362         864 :       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
    1363             :               Value);
    1364             :     }
    1365             :   }
    1366         103 :   const DIType *DTy = resolve(CTy->getBaseType());
    1367             :   if (DTy) {
    1368           2 :     addType(Buffer, DTy);
    1369           2 :     addFlag(Buffer, dwarf::DW_AT_enum_class);
    1370             :   }
    1371         101 : }
    1372             : 
    1373         730 : void DwarfUnit::constructContainingTypeDIEs() {
    1374        1460 :   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
    1375         776 :        CI != CE; ++CI) {
    1376          46 :     DIE &SPDie = *CI->first;
    1377          46 :     const DINode *D = CI->second;
    1378          46 :     if (!D)
    1379           0 :       continue;
    1380          46 :     DIE *NDie = getDIE(D);
    1381          46 :     if (!NDie)
    1382           0 :       continue;
    1383          46 :     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
    1384             :   }
    1385         730 : }
    1386             : 
    1387        3288 : void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
    1388        6576 :   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
    1389        6576 :   StringRef Name = DT->getName();
    1390        3288 :   if (!Name.empty())
    1391        2894 :     addString(MemberDie, dwarf::DW_AT_name, Name);
    1392             : 
    1393        6576 :   addType(MemberDie, resolve(DT->getBaseType()));
    1394             : 
    1395        3288 :   addSourceLine(MemberDie, DT);
    1396             : 
    1397        3668 :   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
    1398             : 
    1399             :     // For C++, virtual base classes are not at fixed offset. Use following
    1400             :     // expression to extract appropriate offset from vtable.
    1401             :     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
    1402             : 
    1403           0 :     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
    1404           0 :     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
    1405           0 :     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
    1406           0 :     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
    1407           0 :     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
    1408           0 :     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
    1409           0 :     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
    1410           0 :     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
    1411             : 
    1412           0 :     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
    1413             :   } else {
    1414        3288 :     uint64_t Size = DT->getSizeInBits();
    1415        3288 :     uint64_t FieldSize = DD->getBaseTypeSize(DT);
    1416        6576 :     uint32_t AlignInBytes = DT->getAlignInBytes();
    1417             :     uint64_t OffsetInBytes;
    1418             : 
    1419        3288 :     bool IsBitfield = FieldSize && Size != FieldSize;
    1420        3288 :     if (IsBitfield) {
    1421             :       // Handle bitfield, assume bytes are 8 bits.
    1422          33 :       if (DD->useDWARF2Bitfields())
    1423          60 :         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
    1424          66 :       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
    1425             : 
    1426          33 :       uint64_t Offset = DT->getOffsetInBits();
    1427             :       // We can't use DT->getAlignInBits() here: AlignInBits for member type
    1428             :       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
    1429             :       // which can't be done with bitfields. Thus we use FieldSize here.
    1430          33 :       uint32_t AlignInBits = FieldSize;
    1431          33 :       uint32_t AlignMask = ~(AlignInBits - 1);
    1432             :       // The bits from the start of the storage unit to the start of the field.
    1433          33 :       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
    1434             :       // The byte offset of the field's aligned storage unit inside the struct.
    1435          33 :       OffsetInBytes = (Offset - StartBitOffset) / 8;
    1436             : 
    1437          33 :       if (DD->useDWARF2Bitfields()) {
    1438          20 :         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
    1439          20 :         uint64_t FieldOffset = (HiMark - FieldSize);
    1440          20 :         Offset -= FieldOffset;
    1441             : 
    1442             :         // Maybe we need to work from the other end.
    1443          20 :         if (Asm->getDataLayout().isLittleEndian())
    1444          17 :           Offset = FieldSize - (Offset + Size);
    1445             : 
    1446          40 :         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
    1447          20 :         OffsetInBytes = FieldOffset >> 3;
    1448             :       } else {
    1449          26 :         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
    1450             :       }
    1451             :     } else {
    1452             :       // This is not a bitfield.
    1453        3255 :       OffsetInBytes = DT->getOffsetInBits() / 8;
    1454        3255 :       if (AlignInBytes)
    1455         708 :         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
    1456             :                 AlignInBytes);
    1457             :     }
    1458             : 
    1459        3288 :     if (DD->getDwarfVersion() <= 2) {
    1460         273 :       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
    1461          91 :       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
    1462          91 :       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
    1463          91 :       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
    1464        3197 :     } else if (!IsBitfield || DD->useDWARF2Bitfields())
    1465        6368 :       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
    1466             :               OffsetInBytes);
    1467             :   }
    1468             : 
    1469        6576 :   if (DT->isProtected())
    1470         423 :     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1471             :             dwarf::DW_ACCESS_protected);
    1472        6294 :   else if (DT->isPrivate())
    1473         327 :     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1474             :             dwarf::DW_ACCESS_private);
    1475             :   // Otherwise C++ member and base classes are considered public.
    1476        6076 :   else if (DT->isPublic())
    1477         399 :     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1478             :             dwarf::DW_ACCESS_public);
    1479        6576 :   if (DT->isVirtual())
    1480           0 :     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
    1481             :             dwarf::DW_VIRTUALITY_virtual);
    1482             : 
    1483             :   // Objective-C properties.
    1484           5 :   if (DINode *PNode = DT->getObjCProperty())
    1485           5 :     if (DIE *PDie = getDIE(PNode))
    1486           0 :       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
    1487           0 :                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
    1488             : 
    1489        6576 :   if (DT->isArtificial())
    1490          13 :     addFlag(MemberDie, dwarf::DW_AT_artificial);
    1491        3288 : }
    1492             : 
    1493         249 : DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
    1494         249 :   if (!DT)
    1495             :     return nullptr;
    1496             : 
    1497             :   // Construct the context before querying for the existence of the DIE in case
    1498             :   // such construction creates the DIE.
    1499         747 :   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
    1500             :   assert(dwarf::isType(ContextDIE->getTag()) &&
    1501             :          "Static member should belong to a type.");
    1502             : 
    1503         249 :   if (DIE *StaticMemberDIE = getDIE(DT))
    1504             :     return StaticMemberDIE;
    1505             : 
    1506         460 :   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
    1507             : 
    1508         460 :   const DIType *Ty = resolve(DT->getBaseType());
    1509             : 
    1510         460 :   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
    1511         230 :   addType(StaticMemberDIE, Ty);
    1512         230 :   addSourceLine(StaticMemberDIE, DT);
    1513         230 :   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
    1514         230 :   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
    1515             : 
    1516             :   // FIXME: We could omit private if the parent is a class_type, and
    1517             :   // public if the parent is something else.
    1518         460 :   if (DT->isProtected())
    1519          12 :     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1520             :             dwarf::DW_ACCESS_protected);
    1521         452 :   else if (DT->isPrivate())
    1522          27 :     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1523             :             dwarf::DW_ACCESS_private);
    1524         434 :   else if (DT->isPublic())
    1525         237 :     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
    1526             :             dwarf::DW_ACCESS_public);
    1527             : 
    1528         432 :   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
    1529         202 :     addConstantValue(StaticMemberDIE, CI, Ty);
    1530         206 :   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
    1531           2 :     addConstantFPValue(StaticMemberDIE, CFP);
    1532             : 
    1533         460 :   if (uint32_t AlignInBytes = DT->getAlignInBytes())
    1534           3 :     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
    1535             :             AlignInBytes);
    1536             : 
    1537             :   return &StaticMemberDIE;
    1538             : }
    1539             : 
    1540         790 : void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
    1541             :   // Emit size of content not including length itself
    1542        2370 :   Asm->OutStreamer->AddComment("Length of Unit");
    1543         790 :   Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
    1544             : 
    1545        2370 :   Asm->OutStreamer->AddComment("DWARF version number");
    1546         790 :   unsigned Version = DD->getDwarfVersion();
    1547         790 :   Asm->EmitInt16(Version);
    1548             : 
    1549             :   // DWARF v5 reorders the address size and adds a unit type.
    1550         790 :   if (Version >= 5) {
    1551          27 :     Asm->OutStreamer->AddComment("DWARF Unit Type");
    1552           9 :     Asm->EmitInt8(UT);
    1553          27 :     Asm->OutStreamer->AddComment("Address Size (in bytes)");
    1554           9 :     Asm->EmitInt8(Asm->MAI->getCodePointerSize());
    1555             :   }
    1556             : 
    1557             :   // We share one abbreviations table across all units so it's always at the
    1558             :   // start of the section. Use a relocatable offset where needed to ensure
    1559             :   // linking doesn't invalidate that offset.
    1560        2370 :   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
    1561         790 :   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
    1562         790 :   if (UseOffsets)
    1563          35 :     Asm->EmitInt32(0);
    1564             :   else
    1565        1510 :     Asm->emitDwarfSymbolReference(
    1566         755 :         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
    1567             : 
    1568         790 :   if (Version <= 4) {
    1569        2343 :     Asm->OutStreamer->AddComment("Address Size (in bytes)");
    1570         781 :     Asm->EmitInt8(Asm->MAI->getCodePointerSize());
    1571             :   }
    1572         790 : }
    1573             : 
    1574          25 : void DwarfTypeUnit::emitHeader(bool UseOffsets) {
    1575          50 :   DwarfUnit::emitCommonHeader(UseOffsets, 
    1576          25 :                               DD->useSplitDwarf() ? dwarf::DW_UT_split_type
    1577             :                                                   : dwarf::DW_UT_type);
    1578          75 :   Asm->OutStreamer->AddComment("Type Signature");
    1579          50 :   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
    1580          75 :   Asm->OutStreamer->AddComment("Type DIE Offset");
    1581             :   // In a skeleton type unit there is no type DIE so emit a zero offset.
    1582          75 :   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
    1583          25 :                                  sizeof(Ty->getOffset()));
    1584          25 : }
    1585             : 
    1586             : DIE::value_iterator
    1587         207 : DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
    1588             :                            const MCSymbol *Hi, const MCSymbol *Lo) {
    1589             :   return Die.addValue(DIEValueAllocator, Attribute,
    1590         207 :                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
    1591             :                                                  : dwarf::DW_FORM_data4,
    1592        1035 :                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
    1593             : }
    1594             : 
    1595             : DIE::value_iterator
    1596       55428 : DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
    1597             :                            const MCSymbol *Label, const MCSymbol *Sec) {
    1598       55428 :   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
    1599             :     return addLabel(Die, Attribute,
    1600       55223 :                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
    1601             :                                                : dwarf::DW_FORM_data4,
    1602       55223 :                     Label);
    1603         205 :   return addSectionDelta(Die, Attribute, Label, Sec);
    1604             : }
    1605             : 
    1606         281 : bool DwarfTypeUnit::isDwoUnit() const {
    1607             :   // Since there are no skeleton type units, all type units are dwo type units
    1608             :   // when split DWARF is being used.
    1609         281 :   return DD->useSplitDwarf();
    1610             : }
    1611             : 
    1612           8 : void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
    1613             :                                   const DIScope *Context) {
    1614           8 :   getCU().addGlobalNameForTypeUnit(Name, Context);
    1615           8 : }
    1616             : 
    1617          66 : void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
    1618             :                                   const DIScope *Context) {
    1619          66 :   getCU().addGlobalTypeUnitType(Ty, Context);
    1620          66 : }
    1621             : 
    1622          54 : const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
    1623          54 :   if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
    1624             :     return nullptr;
    1625          44 :   if (isDwoUnit())
    1626             :     return nullptr;
    1627          41 :   return getSection()->getBeginSymbol();
    1628      216918 : }

Generated by: LCOV version 1.13