Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/AddDiscriminators.cpp
35271 views
//===- AddDiscriminators.cpp - Insert DWARF path discriminators -----------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file adds DWARF discriminators to the IR. Path discriminators are9// used to decide what CFG path was taken inside sub-graphs whose instructions10// share the same line and column number information.11//12// The main user of this is the sample profiler. Instruction samples are13// mapped to line number information. Since a single line may be spread14// out over several basic blocks, discriminators add more precise location15// for the samples.16//17// For example,18//19// 1 #define ASSERT(P)20// 2 if (!(P))21// 3 abort()22// ...23// 100 while (true) {24// 101 ASSERT (sum < 0);25// 102 ...26// 130 }27//28// when converted to IR, this snippet looks something like:29//30// while.body: ; preds = %entry, %if.end31// %0 = load i32* %sum, align 4, !dbg !1532// %cmp = icmp slt i32 %0, 0, !dbg !1533// br i1 %cmp, label %if.end, label %if.then, !dbg !1534//35// if.then: ; preds = %while.body36// call void @abort(), !dbg !1537// br label %if.end, !dbg !1538//39// Notice that all the instructions in blocks 'while.body' and 'if.then'40// have exactly the same debug information. When this program is sampled41// at runtime, the profiler will assume that all these instructions are42// equally frequent. This, in turn, will consider the edge while.body->if.then43// to be frequently taken (which is incorrect).44//45// By adding a discriminator value to the instructions in block 'if.then',46// we can distinguish instructions at line 101 with discriminator 0 from47// the instructions at line 101 with discriminator 1.48//49// For more details about DWARF discriminators, please visit50// http://wiki.dwarfstd.org/index.php?title=Path_Discriminators51//52//===----------------------------------------------------------------------===//5354#include "llvm/Transforms/Utils/AddDiscriminators.h"55#include "llvm/ADT/DenseMap.h"56#include "llvm/ADT/DenseSet.h"57#include "llvm/ADT/StringRef.h"58#include "llvm/IR/BasicBlock.h"59#include "llvm/IR/DebugInfoMetadata.h"60#include "llvm/IR/Function.h"61#include "llvm/IR/Instruction.h"62#include "llvm/IR/Instructions.h"63#include "llvm/IR/IntrinsicInst.h"64#include "llvm/IR/PassManager.h"65#include "llvm/Support/Casting.h"66#include "llvm/Support/CommandLine.h"67#include "llvm/Support/Debug.h"68#include "llvm/Support/raw_ostream.h"69#include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"70#include <utility>7172using namespace llvm;73using namespace sampleprofutil;7475#define DEBUG_TYPE "add-discriminators"7677// Command line option to disable discriminator generation even in the78// presence of debug information. This is only needed when debugging79// debug info generation issues.80static cl::opt<bool> NoDiscriminators(81"no-discriminators", cl::init(false),82cl::desc("Disable generation of discriminator information."));8384static bool shouldHaveDiscriminator(const Instruction *I) {85return !isa<IntrinsicInst>(I) || isa<MemIntrinsic>(I);86}8788/// Assign DWARF discriminators.89///90/// To assign discriminators, we examine the boundaries of every91/// basic block and its successors. Suppose there is a basic block B192/// with successor B2. The last instruction I1 in B1 and the first93/// instruction I2 in B2 are located at the same file and line number.94/// This situation is illustrated in the following code snippet:95///96/// if (i < 10) x = i;97///98/// entry:99/// br i1 %cmp, label %if.then, label %if.end, !dbg !10100/// if.then:101/// %1 = load i32* %i.addr, align 4, !dbg !10102/// store i32 %1, i32* %x, align 4, !dbg !10103/// br label %if.end, !dbg !10104/// if.end:105/// ret void, !dbg !12106///107/// Notice how the branch instruction in block 'entry' and all the108/// instructions in block 'if.then' have the exact same debug location109/// information (!dbg !10).110///111/// To distinguish instructions in block 'entry' from instructions in112/// block 'if.then', we generate a new lexical block for all the113/// instruction in block 'if.then' that share the same file and line114/// location with the last instruction of block 'entry'.115///116/// This new lexical block will have the same location information as117/// the previous one, but with a new DWARF discriminator value.118///119/// One of the main uses of this discriminator value is in runtime120/// sample profilers. It allows the profiler to distinguish instructions121/// at location !dbg !10 that execute on different basic blocks. This is122/// important because while the predicate 'if (x < 10)' may have been123/// executed millions of times, the assignment 'x = i' may have only124/// executed a handful of times (meaning that the entry->if.then edge is125/// seldom taken).126///127/// If we did not have discriminator information, the profiler would128/// assign the same weight to both blocks 'entry' and 'if.then', which129/// in turn will make it conclude that the entry->if.then edge is very130/// hot.131///132/// To decide where to create new discriminator values, this function133/// traverses the CFG and examines instruction at basic block boundaries.134/// If the last instruction I1 of a block B1 is at the same file and line135/// location as instruction I2 of successor B2, then it creates a new136/// lexical block for I2 and all the instruction in B2 that share the same137/// file and line location as I2. This new lexical block will have a138/// different discriminator number than I1.139static bool addDiscriminators(Function &F) {140// If the function has debug information, but the user has disabled141// discriminators, do nothing.142// Simlarly, if the function has no debug info, do nothing.143if (NoDiscriminators || !F.getSubprogram())144return false;145146// Create FSDiscriminatorVariable if flow sensitive discriminators are used.147if (EnableFSDiscriminator)148createFSDiscriminatorVariable(F.getParent());149150bool Changed = false;151152using Location = std::pair<StringRef, unsigned>;153using BBSet = DenseSet<const BasicBlock *>;154using LocationBBMap = DenseMap<Location, BBSet>;155using LocationDiscriminatorMap = DenseMap<Location, unsigned>;156using LocationSet = DenseSet<Location>;157158LocationBBMap LBM;159LocationDiscriminatorMap LDM;160161// Traverse all instructions in the function. If the source line location162// of the instruction appears in other basic block, assign a new163// discriminator for this instruction.164for (BasicBlock &B : F) {165for (auto &I : B) {166// Not all intrinsic calls should have a discriminator.167// We want to avoid a non-deterministic assignment of discriminators at168// different debug levels. We still allow discriminators on memory169// intrinsic calls because those can be early expanded by SROA into170// pairs of loads and stores, and the expanded load/store instructions171// should have a valid discriminator.172if (!shouldHaveDiscriminator(&I))173continue;174const DILocation *DIL = I.getDebugLoc();175if (!DIL)176continue;177Location L = std::make_pair(DIL->getFilename(), DIL->getLine());178auto &BBMap = LBM[L];179auto R = BBMap.insert(&B);180if (BBMap.size() == 1)181continue;182// If we could insert more than one block with the same line+file, a183// discriminator is needed to distinguish both instructions.184// Only the lowest 7 bits are used to represent a discriminator to fit185// it in 1 byte ULEB128 representation.186unsigned Discriminator = R.second ? ++LDM[L] : LDM[L];187auto NewDIL = DIL->cloneWithBaseDiscriminator(Discriminator);188if (!NewDIL) {189LLVM_DEBUG(dbgs() << "Could not encode discriminator: "190<< DIL->getFilename() << ":" << DIL->getLine() << ":"191<< DIL->getColumn() << ":" << Discriminator << " "192<< I << "\n");193} else {194I.setDebugLoc(*NewDIL);195LLVM_DEBUG(dbgs() << DIL->getFilename() << ":" << DIL->getLine() << ":"196<< DIL->getColumn() << ":" << Discriminator << " " << I197<< "\n");198}199Changed = true;200}201}202203// Traverse all instructions and assign new discriminators to call204// instructions with the same lineno that are in the same basic block.205// Sample base profile needs to distinguish different function calls within206// a same source line for correct profile annotation.207for (BasicBlock &B : F) {208LocationSet CallLocations;209for (auto &I : B) {210// We bypass intrinsic calls for the following two reasons:211// 1) We want to avoid a non-deterministic assignment of212// discriminators.213// 2) We want to minimize the number of base discriminators used.214if (!isa<InvokeInst>(I) && (!isa<CallInst>(I) || isa<IntrinsicInst>(I)))215continue;216217DILocation *CurrentDIL = I.getDebugLoc();218if (!CurrentDIL)219continue;220Location L =221std::make_pair(CurrentDIL->getFilename(), CurrentDIL->getLine());222if (!CallLocations.insert(L).second) {223unsigned Discriminator = ++LDM[L];224auto NewDIL = CurrentDIL->cloneWithBaseDiscriminator(Discriminator);225if (!NewDIL) {226LLVM_DEBUG(dbgs()227<< "Could not encode discriminator: "228<< CurrentDIL->getFilename() << ":"229<< CurrentDIL->getLine() << ":" << CurrentDIL->getColumn()230<< ":" << Discriminator << " " << I << "\n");231} else {232I.setDebugLoc(*NewDIL);233Changed = true;234}235}236}237}238return Changed;239}240241PreservedAnalyses AddDiscriminatorsPass::run(Function &F,242FunctionAnalysisManager &AM) {243if (!addDiscriminators(F))244return PreservedAnalyses::all();245246// FIXME: should be all()247return PreservedAnalyses::none();248}249250251