MC CFG: Add MCObjectDisassembler support for entrypoint + static ctors.
[oota-llvm.git] / lib / MC / MCObjectDisassembler.cpp
1 //===- lib/MC/MCObjectDisassembler.cpp ------------------------------------===//
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 #include "llvm/MC/MCObjectDisassembler.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCAtom.h"
17 #include "llvm/MC/MCDisassembler.h"
18 #include "llvm/MC/MCFunction.h"
19 #include "llvm/MC/MCInstrAnalysis.h"
20 #include "llvm/MC/MCModule.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/MemoryObject.h"
23 #include "llvm/Support/StringRefMemoryObject.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <map>
26 #include <set>
27
28 using namespace llvm;
29 using namespace object;
30
31 MCObjectDisassembler::MCObjectDisassembler(const ObjectFile &Obj,
32                                            const MCDisassembler &Dis,
33                                            const MCInstrAnalysis &MIA)
34   : Obj(Obj), Dis(Dis), MIA(MIA) {}
35
36 uint64_t MCObjectDisassembler::getEntrypoint() {
37   error_code ec;
38   for (symbol_iterator SI = Obj.begin_symbols(), SE = Obj.end_symbols();
39        SI != SE; SI.increment(ec)) {
40     if (ec)
41       break;
42     StringRef Name;
43     SI->getName(Name);
44     if (Name == "main" || Name == "_main") {
45       uint64_t Entrypoint;
46       SI->getAddress(Entrypoint);
47       return Entrypoint;
48     }
49   }
50   return 0;
51 }
52
53 ArrayRef<uint64_t> MCObjectDisassembler::getStaticInitFunctions() {
54   return ArrayRef<uint64_t>();
55 }
56
57 ArrayRef<uint64_t> MCObjectDisassembler::getStaticExitFunctions() {
58   return ArrayRef<uint64_t>();
59 }
60
61 MCModule *MCObjectDisassembler::buildEmptyModule() {
62   MCModule *Module = new MCModule;
63   Module->Entrypoint = getEntrypoint();
64   return Module;
65 }
66
67 MCModule *MCObjectDisassembler::buildModule(bool withCFG) {
68   MCModule *Module = buildEmptyModule();
69
70   buildSectionAtoms(Module);
71   if (withCFG)
72     buildCFG(Module);
73   return Module;
74 }
75
76 void MCObjectDisassembler::buildSectionAtoms(MCModule *Module) {
77   error_code ec;
78   for (section_iterator SI = Obj.begin_sections(),
79                         SE = Obj.end_sections();
80                         SI != SE;
81                         SI.increment(ec)) {
82     if (ec) break;
83
84     bool isText; SI->isText(isText);
85     bool isData; SI->isData(isData);
86     if (!isData && !isText)
87       continue;
88
89     uint64_t StartAddr; SI->getAddress(StartAddr);
90     uint64_t SecSize; SI->getSize(SecSize);
91     if (StartAddr == UnknownAddressOrSize || SecSize == UnknownAddressOrSize)
92       continue;
93
94     StringRef Contents; SI->getContents(Contents);
95     StringRefMemoryObject memoryObject(Contents, StartAddr);
96
97     // We don't care about things like non-file-backed sections yet.
98     if (Contents.size() != SecSize || !SecSize)
99       continue;
100     uint64_t EndAddr = StartAddr + SecSize - 1;
101
102     StringRef SecName; SI->getName(SecName);
103
104     if (isText) {
105       MCTextAtom *Text = Module->createTextAtom(StartAddr, EndAddr);
106       Text->setName(SecName);
107       uint64_t InstSize;
108       for (uint64_t Index = 0; Index < SecSize; Index += InstSize) {
109         MCInst Inst;
110         if (Dis.getInstruction(Inst, InstSize, memoryObject, Index,
111                                nulls(), nulls()))
112           Text->addInst(Inst, InstSize);
113         else
114           // We don't care about splitting mixed atoms either.
115           llvm_unreachable("Couldn't disassemble instruction in atom.");
116       }
117
118     } else {
119       MCDataAtom *Data = Module->createDataAtom(StartAddr, EndAddr);
120       Data->setName(SecName);
121       for (uint64_t Index = 0; Index < SecSize; ++Index)
122         Data->addData(Contents[Index]);
123     }
124   }
125 }
126
127 namespace {
128   struct BBInfo;
129   typedef std::set<BBInfo*> BBInfoSetTy;
130
131   struct BBInfo {
132     MCTextAtom *Atom;
133     MCBasicBlock *BB;
134     BBInfoSetTy Succs;
135     BBInfoSetTy Preds;
136
137     void addSucc(BBInfo &Succ) {
138       Succs.insert(&Succ);
139       Succ.Preds.insert(this);
140     }
141   };
142 }
143
144 void MCObjectDisassembler::buildCFG(MCModule *Module) {
145   typedef std::map<uint64_t, BBInfo> BBInfoByAddrTy;
146   BBInfoByAddrTy BBInfos;
147   typedef std::set<uint64_t> AddressSetTy;
148   AddressSetTy Splits;
149   AddressSetTy Calls;
150
151   error_code ec;
152   for (symbol_iterator SI = Obj.begin_symbols(), SE = Obj.end_symbols();
153        SI != SE; SI.increment(ec)) {
154     if (ec)
155       break;
156     SymbolRef::Type SymType;
157     SI->getType(SymType);
158     if (SymType == SymbolRef::ST_Function) {
159       uint64_t SymAddr;
160       SI->getAddress(SymAddr);
161       Calls.insert(SymAddr);
162       Splits.insert(SymAddr);
163     }
164   }
165
166   assert(Module->func_begin() == Module->func_end()
167          && "Module already has a CFG!");
168
169   // First, determine the basic block boundaries and call targets.
170   for (MCModule::atom_iterator AI = Module->atom_begin(),
171                                AE = Module->atom_end();
172        AI != AE; ++AI) {
173     MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI);
174     if (!TA) continue;
175     Calls.insert(TA->getBeginAddr());
176     BBInfos[TA->getBeginAddr()].Atom = TA;
177     for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
178          II != IE; ++II) {
179       if (MIA.isTerminator(II->Inst))
180         Splits.insert(II->Address + II->Size);
181       uint64_t Target;
182       if (MIA.evaluateBranch(II->Inst, II->Address, II->Size, Target)) {
183         if (MIA.isCall(II->Inst))
184           Calls.insert(Target);
185         Splits.insert(Target);
186       }
187     }
188   }
189
190   // Split text atoms into basic block atoms.
191   for (AddressSetTy::const_iterator SI = Splits.begin(), SE = Splits.end();
192        SI != SE; ++SI) {
193     MCAtom *A = Module->findAtomContaining(*SI);
194     if (!A) continue;
195     MCTextAtom *TA = cast<MCTextAtom>(A);
196     if (TA->getBeginAddr() == *SI)
197       continue;
198     MCTextAtom *NewAtom = TA->split(*SI);
199     BBInfos[NewAtom->getBeginAddr()].Atom = NewAtom;
200     StringRef BBName = TA->getName();
201     BBName = BBName.substr(0, BBName.find_last_of(':'));
202     NewAtom->setName((BBName + ":" + utohexstr(*SI)).str());
203   }
204
205   // Compute succs/preds.
206   for (MCModule::atom_iterator AI = Module->atom_begin(),
207                                AE = Module->atom_end();
208                                AI != AE; ++AI) {
209     MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI);
210     if (!TA) continue;
211     BBInfo &CurBB = BBInfos[TA->getBeginAddr()];
212     const MCDecodedInst &LI = TA->back();
213     if (MIA.isBranch(LI.Inst)) {
214       uint64_t Target;
215       if (MIA.evaluateBranch(LI.Inst, LI.Address, LI.Size, Target))
216         CurBB.addSucc(BBInfos[Target]);
217       if (MIA.isConditionalBranch(LI.Inst))
218         CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
219     } else if (!MIA.isTerminator(LI.Inst))
220       CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
221   }
222
223
224   // Create functions and basic blocks.
225   for (AddressSetTy::const_iterator CI = Calls.begin(), CE = Calls.end();
226        CI != CE; ++CI) {
227     BBInfo &BBI = BBInfos[*CI];
228     if (!BBI.Atom) continue;
229
230     MCFunction &MCFN = *Module->createFunction(BBI.Atom->getName());
231
232     // Create MCBBs.
233     SmallSetVector<BBInfo*, 16> Worklist;
234     Worklist.insert(&BBI);
235     for (size_t WI = 0; WI < Worklist.size(); ++WI) {
236       BBInfo *BBI = Worklist[WI];
237       if (!BBI->Atom)
238         continue;
239       BBI->BB = &MCFN.createBlock(*BBI->Atom);
240       // Add all predecessors and successors to the worklist.
241       for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
242                                  SI != SE; ++SI)
243         Worklist.insert(*SI);
244       for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
245                                  PI != PE; ++PI)
246         Worklist.insert(*PI);
247     }
248
249     // Set preds/succs.
250     for (size_t WI = 0; WI < Worklist.size(); ++WI) {
251       BBInfo *BBI = Worklist[WI];
252       MCBasicBlock *MCBB = BBI->BB;
253       if (!MCBB)
254         continue;
255       for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
256                                  SI != SE; ++SI)
257         MCBB->addSuccessor((*SI)->BB);
258       for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
259                                  PI != PE; ++PI)
260         MCBB->addPredecessor((*PI)->BB);
261     }
262   }
263 }