Esempio n. 1
0
void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
  if (!Loc)
    return;
  InitializeTypeMap(M);
  processScope(Loc.getScope());
  processLocation(M, Loc.getOrigLocation());
}
Esempio n. 2
0
void LineNumberAnnotatedWriter::emitInstructionAnnot(
      const Instruction *I, formatted_raw_ostream &Out)
{
    DILocation *NewInstrLoc = I->getDebugLoc();
    if (!NewInstrLoc) {
        auto Loc = DebugLoc.find(I);
        if (Loc != DebugLoc.end())
            NewInstrLoc = Loc->second;
    }
    if (!NewInstrLoc || NewInstrLoc == InstrLoc)
        return;
    InstrLoc = NewInstrLoc;
    std::vector<DILineInfo> DIvec;
    do {
        DIvec.emplace_back();
        DILineInfo &DI = DIvec.back();
        DIScope *scope = NewInstrLoc->getScope();
        if (scope)
            DI.FunctionName = scope->getName();
        DI.FileName = NewInstrLoc->getFilename();
        DI.Line = NewInstrLoc->getLine();
        NewInstrLoc = NewInstrLoc->getInlinedAt();
    } while (NewInstrLoc);
    LinePrinter.emit_lineinfo(Out, DIvec);
}
Esempio n. 3
0
void DiagnosticInfoOptimizationBase::getLocation(StringRef *Filename,
                                                 unsigned *Line,
                                                 unsigned *Column) const {
  DILocation *L = getDebugLoc();
  assert(L != nullptr && "debug location is invalid");
  *Filename = L->getFilename();
  *Line = L->getLine();
  *Column = L->getColumn();
}
Esempio n. 4
0
static std::string getDSPIPath(DILocation Loc) {
  std::string dir = Loc.getDirectory();
  std::string file = Loc.getFilename();
  if (dir.empty()) {
    return file;
  } else if (*dir.rbegin() == '/') {
    return dir + file;
  } else {
    return dir + "/" + file;
  }
}
Esempio n. 5
0
/// processLocation - Process DILocation.
void DebugInfoFinder::processLocation(DILocation Loc) {
  if (!Loc.Verify()) return;
  DIDescriptor S(Loc.getScope());
  if (S.isCompileUnit())
    addCompileUnit(DICompileUnit(S));
  else if (S.isSubprogram())
    processSubprogram(DISubprogram(S));
  else if (S.isLexicalBlock())
    processLexicalBlock(DILexicalBlock(S));
  processLocation(Loc.getOrigLocation());
}
Esempio n. 6
0
/// processLocation - Process DILocation.
void DebugInfoFinder::processLocation(DILocation Loc) {
  if (Loc.isNull()) return;
  DIScope S(Loc.getScope().getNode());
  if (S.isNull()) return;
  if (S.isCompileUnit())
    addCompileUnit(DICompileUnit(S.getNode()));
  else if (S.isSubprogram())
    processSubprogram(DISubprogram(S.getNode()));
  else if (S.isLexicalBlock())
    processLexicalBlock(DILexicalBlock(S.getNode()));
  processLocation(Loc.getOrigLocation());
}
Esempio n. 7
0
/// \brief Get the weight for an instruction.
///
/// The "weight" of an instruction \p Inst is the number of samples
/// collected on that instruction at runtime. To retrieve it, we
/// need to compute the line number of \p Inst relative to the start of its
/// function. We use HeaderLineno to compute the offset. We then
/// look up the samples collected for \p Inst using BodySamples.
///
/// \param Inst Instruction to query.
///
/// \returns The profiled weight of I.
unsigned SampleProfileLoader::getInstWeight(Instruction &Inst) {
  DebugLoc DLoc = Inst.getDebugLoc();
  if (!DLoc)
    return 0;

  unsigned Lineno = DLoc.getLine();
  if (Lineno < HeaderLineno)
    return 0;

  DILocation DIL = DLoc.get();
  int LOffset = Lineno - HeaderLineno;
  unsigned Discriminator = DIL.getDiscriminator();
  unsigned Weight = Samples->samplesAt(LOffset, Discriminator);
  DEBUG(dbgs() << "    " << Lineno << "." << Discriminator << ":" << Inst
               << " (line offset: " << LOffset << "." << Discriminator
               << " - weight: " << Weight << ")\n");
  return Weight;
}
Esempio n. 8
0
/// CreateLocation - Creates a debug info location.
DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
                                     DIScope S, DILocation OrigLoc) {
  Value *Elts[] = {
    ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
    ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
    S.getNode(),
    OrigLoc.getNode(),
  };
  return DILocation(MDNode::get(VMContext, &Elts[0], 4));
}
Esempio n. 9
0
static MDNode *UpdateInlinedAtInfo(MDNode *InsnMD, MDNode *TheCallMD) {
  DILocation ILoc(InsnMD);
  if (!ILoc.Verify()) return InsnMD;

  DILocation CallLoc(TheCallMD);
  if (!CallLoc.Verify()) return InsnMD;

  DILocation OrigLocation = ILoc.getOrigLocation();
  MDNode *NewLoc = TheCallMD;
  if (OrigLocation.Verify())
    NewLoc = UpdateInlinedAtInfo(OrigLocation, TheCallMD);

  Value *MDVs[] = {
    InsnMD->getOperand(0), // Line
    InsnMD->getOperand(1), // Col
    InsnMD->getOperand(2), // Scope
    NewLoc
  };
  return MDNode::get(InsnMD->getContext(), MDVs, 4);
}
Esempio n. 10
0
static MDNode *UpdateInlinedAtInfo(MDNode *InsnMD, MDNode *TheCallMD,
                                   LLVMContext &Context) {
  DILocation ILoc(InsnMD);
  if (ILoc.isNull()) return InsnMD;

  DILocation CallLoc(TheCallMD);
  if (CallLoc.isNull()) return InsnMD;

  DILocation OrigLocation = ILoc.getOrigLocation();
  MDNode *NewLoc = TheCallMD;
  if (!OrigLocation.isNull())
    NewLoc = UpdateInlinedAtInfo(OrigLocation.getNode(), TheCallMD, Context);

  SmallVector<Value *, 4> MDVs;
  MDVs.push_back(InsnMD->getElement(0)); // Line
  MDVs.push_back(InsnMD->getElement(1)); // Col
  MDVs.push_back(InsnMD->getElement(2)); // Scope
  MDVs.push_back(NewLoc);
  return MDNode::get(Context, MDVs.data(), MDVs.size());
}
Esempio n. 11
0
//
// Function: printSourceInfo()
//
// Description:
//  Print source file and line number information about the instruction to
//  standard output.
//
static void
printSourceInfo (std::string errorType, Instruction * I) {
  //
  // Print out where the fault will be inserted in the source code.
  // If we can't find the source line information, use a dummy line number and
  // the function name by default.
  //
  std::string fname = I->getParent()->getParent()->getNameStr();
  std::string funcname = fname;
  uint64_t lineno = 0;
  unsigned dbgKind = I->getContext().getMDKindID("dbg");
  if (MDNode *Dbg = I->getMetadata(dbgKind)) {
    DILocation Loc (Dbg);
    fname = Loc.getDirectory().str() + Loc.getFilename().str();
    lineno   = Loc.getLineNumber();
  }

  std::cout << "Inject: " << errorType << ": "
            << funcname   << ": " << fname << ": " << lineno << "\n";
  return;
}
Esempio n. 12
0
void
CallGraphPass::handleInstruction(llvm::CallSite cs, callgraphs::FunctionInfo *fun, llvm::Module &m){
  // Check whether the instruction is actually a call
  if (!cs.getInstruction()) {
    return;
  }

  // Check whether the called function is directly invoked
  auto called = dyn_cast<Function>(cs.getCalledValue()->stripPointerCasts());
  if (!called) {
    for(auto &f : m){
      if(f.hasAddressTaken()){
        
        bool match = true;
        std::vector< Type* > argslist;
        for (Use &U : cs.getInstruction()->operands()) {
          Value *v = U.get();
          argslist.push_back( v->getType() ); 
        }
        
        llvm::Function::ArgumentListType &alt = f.getArgumentList();
        int j = 0;
        for( auto &a : alt){
          if( a.getType() != argslist[j++]){
            match = false;
         }
        }
        
        if( argslist.size() > (j+1) && !f.isVarArg() ){
          match = false;
        }
        
        if(match){
          DILocation *Loc = cs.getInstruction()->getDebugLoc();
          callgraphs::CallInfo ci( &f, Loc->getLine() , Loc->getFilename(),
                                  funcs.find( fun->getFunction() )->second.callCount);
          funcs.find( &f )->second.weight++;
          funcs.find( fun->getFunction() )->second.directCalls.push_back( ci );
        }
        
        
      }
    }
    funcs.find( fun->getFunction() )->second.callCount++;
    return;
  }

  if(called->getName() == "llvm.dbg.declare")
    return;
    
  // Direct Calls heres
  DILocation *Loc = cs.getInstruction()->getDebugLoc();
  callgraphs::CallInfo ci(called, Loc->getLine() , Loc->getFilename(), 
    funcs.find( fun->getFunction() )->second.callCount  );
  funcs.find( called )->second.weight++;
  funcs.find( fun->getFunction() )->second.directCalls.push_back( ci );
  funcs.find( fun->getFunction() )->second.callCount++;
  
}
Esempio n. 13
0
  /// ExtractDebugLocation - Extract debug location information
  /// from DILocation.
  DebugLoc ExtractDebugLocation(DILocation &Loc,
                                DebugLocTracker &DebugLocInfo) {
    DebugLoc DL;
    MDNode *Context = Loc.getScope().getNode();
    MDNode *InlinedLoc = NULL;
    if (!Loc.getOrigLocation().isNull())
      InlinedLoc = Loc.getOrigLocation().getNode();
    // If this location is already tracked then use it.
    DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
                        Loc.getColumnNumber());
    DenseMap<DebugLocTuple, unsigned>::iterator II
      = DebugLocInfo.DebugIdMap.find(Tuple);
    if (II != DebugLocInfo.DebugIdMap.end())
      return DebugLoc::get(II->second);

    // Add a new location entry.
    unsigned Id = DebugLocInfo.DebugLocations.size();
    DebugLocInfo.DebugLocations.push_back(Tuple);
    DebugLocInfo.DebugIdMap[Tuple] = Id;

    return DebugLoc::get(Id);
  }
Esempio n. 14
0
const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
                                                const DILocation *LocB,
                                                bool GenerateLocation) {
  if (!LocA || !LocB)
    return nullptr;

  if (LocA == LocB || !LocA->canDiscriminate(*LocB))
    return LocA;

  if (!GenerateLocation)
    return nullptr;

  SmallPtrSet<DILocation *, 5> InlinedLocationsA;
  for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
    InlinedLocationsA.insert(L);
  const DILocation *Result = LocB;
  for (DILocation *L = LocB->getInlinedAt(); L; L = L->getInlinedAt()) {
    Result = L;
    if (InlinedLocationsA.count(L))
      break;
  }
  return DILocation::get(Result->getContext(), 0, 0, Result->getScope(),
                         Result->getInlinedAt());
}
Esempio n. 15
0
const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
                                                const DILocation *LocB) {
  if (!LocA || !LocB)
    return nullptr;

  if (LocA == LocB)
    return LocA;

  SmallPtrSet<DILocation *, 5> InlinedLocationsA;
  for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
    InlinedLocationsA.insert(L);
  SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
  DIScope *S = LocA->getScope();
  DILocation *L = LocA->getInlinedAt();
  while (S) {
    Locations.insert(std::make_pair(S, L));
    S = S->getScope().resolve();
    if (!S && L) {
      S = L->getScope();
      L = L->getInlinedAt();
    }
  }
  const DILocation *Result = LocB;
  S = LocB->getScope();
  L = LocB->getInlinedAt();
  while (S) {
    if (Locations.count(std::make_pair(S, L)))
      break;
    S = S->getScope().resolve();
    if (!S && L) {
      S = L->getScope();
      L = L->getInlinedAt();
    }
  }

  // If the two locations are irreconsilable, just pick one. This is misleading,
  // but on the other hand, it's a "line 0" location.
  if (!S || !isa<DILocalScope>(S))
    S = LocA->getScope();
  return DILocation::get(Result->getContext(), 0, 0, S, L);
}
Esempio n. 16
0
/// processLocation - Process DILocation.
void DebugInfoFinder::processLocation(DILocation Loc) {
  if (!Loc) return;
  processScope(Loc.getScope());
  processLocation(Loc.getOrigLocation());
}
Esempio n. 17
0
  bool runOnFunction(Function &F) override {
    DecoupleLoopsPass &DLP = Pass::getAnalysis<DecoupleLoopsPass>();

    const LoopInfo *LI = DLP.getLI(&F);

    DIFile *File = nullptr; // The file in which this loop is defined.
    vector<int> lines;      // Line per instruction in the order of traversal.
    vector<int> cols;       // Column per instruction in the order of traversal.
    vector<int> BBs;        // Basic-block for each line.
    vector<int> Loops;        // Loop for each line.
    vector<bool> branchLines; // true if instruction n is a branch instruction
    vector<bool> workLines;
    vector<bool> iterLines;

    int bb_count = 0;
    int loop_count = 0;

    for (Loop *L : *LI) {
      // Ignore loops we cannot decouple.
      if (!DLP.hasWork(L))
        continue;
      for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
           BI != BE; ++BI, ++bb_count) {
        BasicBlock *BB = *BI;
        for (Instruction &Inst : *BB) {
          DILocation *Loc = Inst.getDebugLoc();
          if (!Loc) {
            continue;
          }

          if (!File) {
            File = Loc->getFile();
          }
          int line = Loc->getLine();
          int col = Loc->getColumn();

          lines.push_back(line);
          cols.push_back(col);
          BBs.push_back(bb_count);
          Loops.push_back(loop_count);

          branchLines.push_back(dyn_cast<BranchInst>(&Inst) ? true : false);
          workLines.push_back(DLP.isWork(Inst, L) ? true : false);
          iterLines.push_back(DLP.isIter(Inst, L) ? true : false);
        }
      }
      ++loop_count;
    }

    if (File != nullptr) {
      int prevLoop = -1;
      raw_os_ostream roos(cout);
      for (int i = 0; i < lines.size(); ++i) {
        int line = lines[i];
        if (line == -1)
          continue; // Already traversed.

        if (Loops[i] != prevLoop) {
          prevLoop = Loops[i];
          roos << "Loop " << Loops[i] << "\n";
        }
        roos << File->getFilename() << ":" << line;
        int prevBB = -1;
        for (int j = 0; j < lines.size(); ++j) {
          if (lines[j] != line)
            continue;

          // Destructive and messy (and slow).
          lines[j] = -1;
          if (BBs[j] != prevBB) {
            prevBB = BBs[j];
            roos << " ; BB" << BBs[j] << ":";
          }
          roos << " " << cols[j] << ":";
          if (branchLines[j])
            roos << "b-";
          if (workLines[j])
            roos << "w";
          if (iterLines[j])
            roos << "i";
        }
        roos << '\n';
      }
    } else {
      llvm::errs() << "ERROR: No debugging information found!\n";
    }

    return false;
  }
Esempio n. 18
0
/// \brief Assign DWARF discriminators.
///
/// To assign discriminators, we examine the boundaries of every
/// basic block and its successors. Suppose there is a basic block B1
/// with successor B2. The last instruction I1 in B1 and the first
/// instruction I2 in B2 are located at the same file and line number.
/// This situation is illustrated in the following code snippet:
///
///       if (i < 10) x = i;
///
///     entry:
///       br i1 %cmp, label %if.then, label %if.end, !dbg !10
///     if.then:
///       %1 = load i32* %i.addr, align 4, !dbg !10
///       store i32 %1, i32* %x, align 4, !dbg !10
///       br label %if.end, !dbg !10
///     if.end:
///       ret void, !dbg !12
///
/// Notice how the branch instruction in block 'entry' and all the
/// instructions in block 'if.then' have the exact same debug location
/// information (!dbg !10).
///
/// To distinguish instructions in block 'entry' from instructions in
/// block 'if.then', we generate a new lexical block for all the
/// instruction in block 'if.then' that share the same file and line
/// location with the last instruction of block 'entry'.
///
/// This new lexical block will have the same location information as
/// the previous one, but with a new DWARF discriminator value.
///
/// One of the main uses of this discriminator value is in runtime
/// sample profilers. It allows the profiler to distinguish instructions
/// at location !dbg !10 that execute on different basic blocks. This is
/// important because while the predicate 'if (x < 10)' may have been
/// executed millions of times, the assignment 'x = i' may have only
/// executed a handful of times (meaning that the entry->if.then edge is
/// seldom taken).
///
/// If we did not have discriminator information, the profiler would
/// assign the same weight to both blocks 'entry' and 'if.then', which
/// in turn will make it conclude that the entry->if.then edge is very
/// hot.
///
/// To decide where to create new discriminator values, this function
/// traverses the CFG and examines instruction at basic block boundaries.
/// If the last instruction I1 of a block B1 is at the same file and line
/// location as instruction I2 of successor B2, then it creates a new
/// lexical block for I2 and all the instruction in B2 that share the same
/// file and line location as I2. This new lexical block will have a
/// different discriminator number than I1.
bool AddDiscriminators::runOnFunction(Function &F) {
  // If the function has debug information, but the user has disabled
  // discriminators, do nothing.
  // Simlarly, if the function has no debug info, do nothing.
  // Finally, if this module is built with dwarf versions earlier than 4,
  // do nothing (discriminator support is a DWARF 4 feature).
  if (NoDiscriminators ||
      !hasDebugInfo(F) ||
      F.getParent()->getDwarfVersion() < 4)
    return false;

  bool Changed = false;
  Module *M = F.getParent();
  LLVMContext &Ctx = M->getContext();
  DIBuilder Builder(*M, /*AllowUnresolved*/ false);

  // Traverse all the blocks looking for instructions in different
  // blocks that are at the same file:line location.
  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
    BasicBlock *B = I;
    TerminatorInst *Last = B->getTerminator();
    DILocation LastDIL = Last->getDebugLoc().get();
    if (!LastDIL)
      continue;

    for (unsigned I = 0; I < Last->getNumSuccessors(); ++I) {
      BasicBlock *Succ = Last->getSuccessor(I);
      Instruction *First = Succ->getFirstNonPHIOrDbgOrLifetime();
      DILocation FirstDIL = First->getDebugLoc().get();
      if (!FirstDIL)
        continue;

      // If the first instruction (First) of Succ is at the same file
      // location as B's last instruction (Last), add a new
      // discriminator for First's location and all the instructions
      // in Succ that share the same location with First.
      if (!FirstDIL->canDiscriminate(*LastDIL)) {
        // Create a new lexical scope and compute a new discriminator
        // number for it.
        StringRef Filename = FirstDIL->getFilename();
        auto *Scope = FirstDIL->getScope();
        auto *File = Builder.createFile(Filename, Scope->getDirectory());

        // FIXME: Calculate the discriminator here, based on local information,
        // and delete MDLocation::computeNewDiscriminator().  The current
        // solution gives different results depending on other modules in the
        // same context.  All we really need is to discriminate between
        // FirstDIL and LastDIL -- a local map would suffice.
        unsigned Discriminator = FirstDIL->computeNewDiscriminator();
        auto *NewScope =
            Builder.createLexicalBlockFile(Scope, File, Discriminator);
        auto *NewDIL =
            MDLocation::get(Ctx, FirstDIL->getLine(), FirstDIL->getColumn(),
                            NewScope, FirstDIL->getInlinedAt());
        DebugLoc newDebugLoc = NewDIL;

        // Attach this new debug location to First and every
        // instruction following First that shares the same location.
        for (BasicBlock::iterator I1(*First), E1 = Succ->end(); I1 != E1;
             ++I1) {
          if (I1->getDebugLoc().get() != FirstDIL)
            break;
          I1->setDebugLoc(newDebugLoc);
          DEBUG(dbgs() << NewDIL->getFilename() << ":" << NewDIL->getLine()
                       << ":" << NewDIL->getColumn() << ":"
                       << NewDIL->getDiscriminator() << *I1 << "\n");
        }
        DEBUG(dbgs() << "\n");
        Changed = true;
      }
    }
  }
  return Changed;
}
Esempio n. 19
0
/// \brief Assign DWARF discriminators.
///
/// To assign discriminators, we examine the boundaries of every
/// basic block and its successors. Suppose there is a basic block B1
/// with successor B2. The last instruction I1 in B1 and the first
/// instruction I2 in B2 are located at the same file and line number.
/// This situation is illustrated in the following code snippet:
///
///       if (i < 10) x = i;
///
///     entry:
///       br i1 %cmp, label %if.then, label %if.end, !dbg !10
///     if.then:
///       %1 = load i32* %i.addr, align 4, !dbg !10
///       store i32 %1, i32* %x, align 4, !dbg !10
///       br label %if.end, !dbg !10
///     if.end:
///       ret void, !dbg !12
///
/// Notice how the branch instruction in block 'entry' and all the
/// instructions in block 'if.then' have the exact same debug location
/// information (!dbg !10).
///
/// To distinguish instructions in block 'entry' from instructions in
/// block 'if.then', we generate a new lexical block for all the
/// instruction in block 'if.then' that share the same file and line
/// location with the last instruction of block 'entry'.
///
/// This new lexical block will have the same location information as
/// the previous one, but with a new DWARF discriminator value.
///
/// One of the main uses of this discriminator value is in runtime
/// sample profilers. It allows the profiler to distinguish instructions
/// at location !dbg !10 that execute on different basic blocks. This is
/// important because while the predicate 'if (x < 10)' may have been
/// executed millions of times, the assignment 'x = i' may have only
/// executed a handful of times (meaning that the entry->if.then edge is
/// seldom taken).
///
/// If we did not have discriminator information, the profiler would
/// assign the same weight to both blocks 'entry' and 'if.then', which
/// in turn will make it conclude that the entry->if.then edge is very
/// hot.
///
/// To decide where to create new discriminator values, this function
/// traverses the CFG and examines instruction at basic block boundaries.
/// If the last instruction I1 of a block B1 is at the same file and line
/// location as instruction I2 of successor B2, then it creates a new
/// lexical block for I2 and all the instruction in B2 that share the same
/// file and line location as I2. This new lexical block will have a
/// different discriminator number than I1.
bool AddDiscriminators::runOnFunction(Function &F) {
  // If the function has debug information, but the user has disabled
  // discriminators, do nothing.
  // Simlarly, if the function has no debug info, do nothing.
  // Finally, if this module is built with dwarf versions earlier than 4,
  // do nothing (discriminator support is a DWARF 4 feature).
  if (NoDiscriminators || !hasDebugInfo(F) ||
      F.getParent()->getDwarfVersion() < 4)
    return false;

  bool Changed = false;
  Module *M = F.getParent();
  LLVMContext &Ctx = M->getContext();
  DIBuilder Builder(*M, /*AllowUnresolved*/ false);

  typedef std::pair<StringRef, unsigned> Location;
  typedef DenseMap<const BasicBlock *, Metadata *> BBScopeMap;
  typedef DenseMap<Location, BBScopeMap> LocationBBMap;
  typedef DenseMap<Location, unsigned> LocationDiscriminatorMap;

  LocationBBMap LBM;
  LocationDiscriminatorMap LDM;

  // Traverse all instructions in the function. If the source line location
  // of the instruction appears in other basic block, assign a new
  // discriminator for this instruction.
  for (BasicBlock &B : F) {
    for (auto &I : B.getInstList()) {
      if (isa<DbgInfoIntrinsic>(&I))
        continue;
      const DILocation *DIL = I.getDebugLoc();
      if (!DIL)
        continue;
      Location L = std::make_pair(DIL->getFilename(), DIL->getLine());
      auto &BBMap = LBM[L];
      auto R = BBMap.insert(std::make_pair(&B, (Metadata *)nullptr));
      if (BBMap.size() == 1)
        continue;
      bool InsertSuccess = R.second;
      Metadata *&NewScope = R.first->second;
      // If we could insert a different block in the same location, a
      // discriminator is needed to distinguish both instructions.
      if (InsertSuccess) {
        auto *Scope = DIL->getScope();
        auto *File =
            Builder.createFile(DIL->getFilename(), Scope->getDirectory());
        NewScope = Builder.createLexicalBlockFile(Scope, File, ++LDM[L]);
      }
      I.setDebugLoc(DILocation::get(Ctx, DIL->getLine(), DIL->getColumn(),
                                    NewScope, DIL->getInlinedAt()));
      DEBUG(dbgs() << DIL->getFilename() << ":" << DIL->getLine() << ":"
                   << DIL->getColumn() << ":"
                   << dyn_cast<DILexicalBlockFile>(NewScope)->getDiscriminator()
                   << I << "\n");
      Changed = true;
    }
  }

  // Traverse all instructions and assign new discriminators to call
  // instructions with the same lineno that are in the same basic block.
  // Sample base profile needs to distinguish different function calls within
  // a same source line for correct profile annotation.
  for (BasicBlock &B : F) {
    const DILocation *FirstDIL = nullptr;
    for (auto &I : B.getInstList()) {
      CallInst *Current = dyn_cast<CallInst>(&I);
      if (!Current || isa<DbgInfoIntrinsic>(&I))
        continue;

      DILocation *CurrentDIL = Current->getDebugLoc();
      if (FirstDIL) {
        if (CurrentDIL && CurrentDIL->getLine() == FirstDIL->getLine() &&
            CurrentDIL->getFilename() == FirstDIL->getFilename()) {
          auto *Scope = FirstDIL->getScope();
          auto *File = Builder.createFile(FirstDIL->getFilename(),
                                          Scope->getDirectory());
          Location L =
              std::make_pair(FirstDIL->getFilename(), FirstDIL->getLine());
          auto *NewScope =
              Builder.createLexicalBlockFile(Scope, File, ++LDM[L]);
          Current->setDebugLoc(DILocation::get(
              Ctx, CurrentDIL->getLine(), CurrentDIL->getColumn(), NewScope,
              CurrentDIL->getInlinedAt()));
          Changed = true;
        } else {
          FirstDIL = CurrentDIL;
        }
      } else {
        FirstDIL = CurrentDIL;
      }
    }
  }
  return Changed;
}
void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
  if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
    if (!MN->memoperands_empty()) {
      OS << "<";
      OS << "Mem:";
      for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
           e = MN->memoperands_end(); i != e; ++i) {
        OS << **i;
        if (std::next(i) != e)
          OS << " ";
      }
      OS << ">";
    }
  } else if (const ShuffleVectorSDNode *SVN =
               dyn_cast<ShuffleVectorSDNode>(this)) {
    OS << "<";
    for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
      int Idx = SVN->getMaskElt(i);
      if (i) OS << ",";
      if (Idx < 0)
        OS << "u";
      else
        OS << Idx;
    }
    OS << ">";
  } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
    OS << '<' << CSDN->getAPIntValue() << '>';
  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
    if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
      OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
    else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
      OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
    else {
      OS << "<APFloat(";
      CSDN->getValueAPF().bitcastToAPInt().dump();
      OS << ")>";
    }
  } else if (const GlobalAddressSDNode *GADN =
             dyn_cast<GlobalAddressSDNode>(this)) {
    int64_t offset = GADN->getOffset();
    OS << '<';
    GADN->getGlobal()->printAsOperand(OS);
    OS << '>';
    if (offset > 0)
      OS << " + " << offset;
    else
      OS << " " << offset;
    if (unsigned int TF = GADN->getTargetFlags())
      OS << " [TF=" << TF << ']';
  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
    OS << "<" << FIDN->getIndex() << ">";
  } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
    OS << "<" << JTDN->getIndex() << ">";
    if (unsigned int TF = JTDN->getTargetFlags())
      OS << " [TF=" << TF << ']';
  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
    int offset = CP->getOffset();
    if (CP->isMachineConstantPoolEntry())
      OS << "<" << *CP->getMachineCPVal() << ">";
    else
      OS << "<" << *CP->getConstVal() << ">";
    if (offset > 0)
      OS << " + " << offset;
    else
      OS << " " << offset;
    if (unsigned int TF = CP->getTargetFlags())
      OS << " [TF=" << TF << ']';
  } else if (const TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(this)) {
    OS << "<" << TI->getIndex() << '+' << TI->getOffset() << ">";
    if (unsigned TF = TI->getTargetFlags())
      OS << " [TF=" << TF << ']';
  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
    OS << "<";
    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
    if (LBB)
      OS << LBB->getName() << " ";
    OS << (const void*)BBDN->getBasicBlock() << ">";
  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
    OS << ' ' << PrintReg(R->getReg(),
                          G ? G->getSubtarget().getRegisterInfo() : nullptr);
  } else if (const ExternalSymbolSDNode *ES =
             dyn_cast<ExternalSymbolSDNode>(this)) {
    OS << "'" << ES->getSymbol() << "'";
    if (unsigned int TF = ES->getTargetFlags())
      OS << " [TF=" << TF << ']';
  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
    if (M->getValue())
      OS << "<" << M->getValue() << ">";
    else
      OS << "<null>";
  } else if (const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(this)) {
    if (MD->getMD())
      OS << "<" << MD->getMD() << ">";
    else
      OS << "<null>";
  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
    OS << ":" << N->getVT().getEVTString();
  }
  else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
    OS << "<" << *LD->getMemOperand();

    bool doExt = true;
    switch (LD->getExtensionType()) {
    default: doExt = false; break;
    case ISD::EXTLOAD:  OS << ", anyext"; break;
    case ISD::SEXTLOAD: OS << ", sext"; break;
    case ISD::ZEXTLOAD: OS << ", zext"; break;
    }
    if (doExt)
      OS << " from " << LD->getMemoryVT().getEVTString();

    const char *AM = getIndexedModeName(LD->getAddressingMode());
    if (*AM)
      OS << ", " << AM;

    OS << ">";
  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
    OS << "<" << *ST->getMemOperand();

    if (ST->isTruncatingStore())
      OS << ", trunc to " << ST->getMemoryVT().getEVTString();

    const char *AM = getIndexedModeName(ST->getAddressingMode());
    if (*AM)
      OS << ", " << AM;

    OS << ">";
  } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
    OS << "<" << *M->getMemOperand() << ">";
  } else if (const BlockAddressSDNode *BA =
               dyn_cast<BlockAddressSDNode>(this)) {
    int64_t offset = BA->getOffset();
    OS << "<";
    BA->getBlockAddress()->getFunction()->printAsOperand(OS, false);
    OS << ", ";
    BA->getBlockAddress()->getBasicBlock()->printAsOperand(OS, false);
    OS << ">";
    if (offset > 0)
      OS << " + " << offset;
    else
      OS << " " << offset;
    if (unsigned int TF = BA->getTargetFlags())
      OS << " [TF=" << TF << ']';
  } else if (const AddrSpaceCastSDNode *ASC =
               dyn_cast<AddrSpaceCastSDNode>(this)) {
    OS << '['
       << ASC->getSrcAddressSpace()
       << " -> "
       << ASC->getDestAddressSpace()
       << ']';
  }

  if (unsigned Order = getIROrder())
      OS << " [ORD=" << Order << ']';

  if (getNodeId() != -1)
    OS << " [ID=" << getNodeId() << ']';

  if (!G)
    return;

  DILocation *L = getDebugLoc();
  if (!L)
    return;

  if (auto *Scope = L->getScope())
    OS << Scope->getFilename();
  else
    OS << "<unknown>";
  OS << ':' << L->getLine();
  if (unsigned C = L->getColumn())
    OS << ':' << C;
}