Implement support for the case when a reference to a addr-of-bb
[oota-llvm.git] / lib / CodeGen / MachineModuleInfo.cpp
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
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/CodeGen/MachineModuleInfo.h"
11
12 #include "llvm/Constants.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/GlobalVariable.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Module.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/ErrorHandling.h"
28 using namespace llvm;
29 using namespace llvm::dwarf;
30
31 // Handle the Pass registration stuff necessary to use TargetData's.
32 static RegisterPass<MachineModuleInfo>
33 X("machinemoduleinfo", "Machine Module Information");
34 char MachineModuleInfo::ID = 0;
35
36 // Out of line virtual method.
37 MachineModuleInfoImpl::~MachineModuleInfoImpl() {}
38
39 namespace llvm {
40 class MMIAddrLabelMapCallbackPtr : CallbackVH {
41   MMIAddrLabelMap *Map;
42 public:
43   MMIAddrLabelMapCallbackPtr() : Map(0) {}
44   MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(0) {}
45   
46   void setMap(MMIAddrLabelMap *map) { Map = map; }
47   
48   virtual void deleted();
49   virtual void allUsesReplacedWith(Value *V2);
50 };
51   
52 class MMIAddrLabelMap {
53   MCContext &Context;
54   struct AddrLabelSymEntry {
55     MCSymbol *Sym;  // The symbol for the label.
56     Function *Fn;   // The containing function of the BasicBlock.
57     unsigned Index; // The index in BBCallbacks for the BasicBlock.
58   };
59   
60   DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
61   
62   /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for.  We
63   /// use this so we get notified if a block is deleted or RAUWd.
64   std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
65
66   /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols
67   /// whose corresponding BasicBlock got deleted.  These symbols need to be
68   /// emitted at some point in the file, so AsmPrinter emits them after the
69   /// function body.
70   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
71     DeletedAddrLabelsNeedingEmission;
72 public:
73   
74   MMIAddrLabelMap(MCContext &context) : Context(context) {}
75   ~MMIAddrLabelMap() {
76     assert(DeletedAddrLabelsNeedingEmission.empty() &&
77            "Some labels for deleted blocks never got emitted");
78   }
79   
80   MCSymbol *getAddrLabelSymbol(BasicBlock *BB);  
81   void takeDeletedSymbolsForFunction(Function *F, 
82                                      std::vector<MCSymbol*> &Result);
83
84   void UpdateForDeletedBlock(BasicBlock *BB);
85   void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
86 };
87 }
88
89 MCSymbol *MMIAddrLabelMap::getAddrLabelSymbol(BasicBlock *BB) {
90   assert(BB->hasAddressTaken() &&
91          "Shouldn't get label for block without address taken");
92   AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
93   
94   // If we already had an entry for this block, just return it.
95   if (Entry.Sym) {
96     assert(BB->getParent() == Entry.Fn && "Parent changed");
97     return Entry.Sym;
98   }
99   
100   // Otherwise, this is a new entry, create a new symbol for it and add an
101   // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
102   BBCallbacks.push_back(BB);
103   BBCallbacks.back().setMap(this);
104   Entry.Index = BBCallbacks.size()-1;
105   Entry.Fn = BB->getParent();
106   return Entry.Sym = Context.CreateTempSymbol();
107 }
108
109 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return
110 /// them.
111 void MMIAddrLabelMap::
112 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
113   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
114     DeletedAddrLabelsNeedingEmission.find(F);
115
116   // If there are no entries for the function, just return.
117   if (I == DeletedAddrLabelsNeedingEmission.end()) return;
118   
119   // Otherwise, take the list.
120   std::swap(Result, I->second);
121   DeletedAddrLabelsNeedingEmission.erase(I);
122 }
123
124
125 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
126   // If the block got deleted, there is no need for the symbol.  If the symbol
127   // was already emitted, we can just forget about it, otherwise we need to
128   // queue it up for later emission when the function is output.
129   AddrLabelSymEntry Entry = AddrLabelSymbols[BB];
130   AddrLabelSymbols.erase(BB);
131   assert(Entry.Sym && "Didn't have a symbol, why a callback?");
132   BBCallbacks[Entry.Index] = 0;  // Clear the callback.
133
134   if (Entry.Sym->isDefined())
135     return;
136   
137   // If the block is not yet defined, we need to emit it at the end of the
138   // function.  Add the symbol to the DeletedAddrLabelsNeedingEmission list for
139   // the containing Function.  Since the block is being deleted, its parent may
140   // already be removed, we have to get the function from 'Entry'.
141   assert((BB->getParent() == 0 || BB->getParent() == Entry.Fn) &&
142          "Block/parent mismatch");
143   
144   DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Entry.Sym);
145 }
146
147 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
148   // Get the entry for the RAUW'd block and remove it from our map.
149   AddrLabelSymEntry OldEntry = AddrLabelSymbols[Old];
150   AddrLabelSymbols.erase(Old);
151   assert(OldEntry.Sym && "Didn't have a symbol, why a callback?");
152   
153   // If New is not address taken, just move our symbol over to it.
154   if (!AddrLabelSymbols.count(New)) {
155     BBCallbacks[OldEntry.Index] = New;    // Update the callback.
156     AddrLabelSymbols[New] = OldEntry;     // Set New's entry.
157   } else {
158     assert(0 && "Case not handled yet!");
159     abort();
160   }
161 }
162
163
164 void MMIAddrLabelMapCallbackPtr::deleted() {
165   Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
166 }
167
168 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
169   Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
170 }
171
172
173 //===----------------------------------------------------------------------===//
174
175 MachineModuleInfo::MachineModuleInfo(const MCAsmInfo &MAI)
176 : ImmutablePass(&ID), Context(MAI),
177   ObjFileMMI(0),
178   CurCallSite(0), CallsEHReturn(0), CallsUnwindInit(0), DbgInfoAvailable(false){
179   // Always emit some info, by default "no personality" info.
180   Personalities.push_back(NULL);
181   AddrLabelSymbols = 0;
182 }
183
184 MachineModuleInfo::MachineModuleInfo()
185 : ImmutablePass(&ID), Context(*(MCAsmInfo*)0) {
186   assert(0 && "This MachineModuleInfo constructor should never be called, MMI "
187          "should always be explicitly constructed by LLVMTargetMachine");
188   abort();
189 }
190
191 MachineModuleInfo::~MachineModuleInfo() {
192   delete ObjFileMMI;
193   
194   // FIXME: Why isn't doFinalization being called??
195   //assert(AddrLabelSymbols == 0 && "doFinalization not called");
196   delete AddrLabelSymbols;
197   AddrLabelSymbols = 0;
198 }
199
200 /// doInitialization - Initialize the state for a new module.
201 ///
202 bool MachineModuleInfo::doInitialization() {
203   assert(AddrLabelSymbols == 0 && "Improperly initialized");
204   return false;
205 }
206
207 /// doFinalization - Tear down the state after completion of a module.
208 ///
209 bool MachineModuleInfo::doFinalization() {
210   delete AddrLabelSymbols;
211   AddrLabelSymbols = 0;
212   return false;
213 }
214
215 /// EndFunction - Discard function meta information.
216 ///
217 void MachineModuleInfo::EndFunction() {
218   // Clean up frame info.
219   FrameMoves.clear();
220
221   // Clean up exception info.
222   LandingPads.clear();
223   CallSiteMap.clear();
224   TypeInfos.clear();
225   FilterIds.clear();
226   FilterEnds.clear();
227   CallsEHReturn = 0;
228   CallsUnwindInit = 0;
229   VariableDbgInfo.clear();
230 }
231
232 /// AnalyzeModule - Scan the module for global debug information.
233 ///
234 void MachineModuleInfo::AnalyzeModule(Module &M) {
235   // Insert functions in the llvm.used array (but not llvm.compiler.used) into
236   // UsedFunctions.
237   GlobalVariable *GV = M.getGlobalVariable("llvm.used");
238   if (!GV || !GV->hasInitializer()) return;
239
240   // Should be an array of 'i8*'.
241   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
242   if (InitList == 0) return;
243
244   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
245     if (Function *F =
246           dyn_cast<Function>(InitList->getOperand(i)->stripPointerCasts()))
247       UsedFunctions.insert(F);
248 }
249
250 //===- Address of Block Management ----------------------------------------===//
251
252
253 /// getAddrLabelSymbol - Return the symbol to be used for the specified basic
254 /// block when its address is taken.  This cannot be its normal LBB label
255 /// because the block may be accessed outside its containing function.
256 MCSymbol *MachineModuleInfo::getAddrLabelSymbol(const BasicBlock *BB) {
257   // Lazily create AddrLabelSymbols.
258   if (AddrLabelSymbols == 0)
259     AddrLabelSymbols = new MMIAddrLabelMap(Context);
260   return AddrLabelSymbols->getAddrLabelSymbol(const_cast<BasicBlock*>(BB));
261 }
262
263 /// takeDeletedSymbolsForFunction - If the specified function has had any
264 /// references to address-taken blocks generated, but the block got deleted,
265 /// return the symbol now so we can emit it.  This prevents emitting a
266 /// reference to a symbol that has no definition.
267 void MachineModuleInfo::
268 takeDeletedSymbolsForFunction(const Function *F,
269                               std::vector<MCSymbol*> &Result) {
270   // If no blocks have had their addresses taken, we're done.
271   if (AddrLabelSymbols == 0) return;
272   return AddrLabelSymbols->
273      takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
274 }
275
276 //===- EH -----------------------------------------------------------------===//
277
278 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
279 /// specified MachineBasicBlock.
280 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
281     (MachineBasicBlock *LandingPad) {
282   unsigned N = LandingPads.size();
283   for (unsigned i = 0; i < N; ++i) {
284     LandingPadInfo &LP = LandingPads[i];
285     if (LP.LandingPadBlock == LandingPad)
286       return LP;
287   }
288
289   LandingPads.push_back(LandingPadInfo(LandingPad));
290   return LandingPads[N];
291 }
292
293 /// addInvoke - Provide the begin and end labels of an invoke style call and
294 /// associate it with a try landing pad block.
295 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
296                                   MCSymbol *BeginLabel, MCSymbol *EndLabel) {
297   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
298   LP.BeginLabels.push_back(BeginLabel);
299   LP.EndLabels.push_back(EndLabel);
300 }
301
302 /// addLandingPad - Provide the label of a try LandingPad block.
303 ///
304 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
305   MCSymbol *LandingPadLabel = Context.CreateTempSymbol();
306   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
307   LP.LandingPadLabel = LandingPadLabel;
308   return LandingPadLabel;
309 }
310
311 /// addPersonality - Provide the personality function for the exception
312 /// information.
313 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
314                                        Function *Personality) {
315   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
316   LP.Personality = Personality;
317
318   for (unsigned i = 0; i < Personalities.size(); ++i)
319     if (Personalities[i] == Personality)
320       return;
321
322   // If this is the first personality we're adding go
323   // ahead and add it at the beginning.
324   if (Personalities[0] == NULL)
325     Personalities[0] = Personality;
326   else
327     Personalities.push_back(Personality);
328 }
329
330 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
331 ///
332 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
333                                         std::vector<GlobalVariable *> &TyInfo) {
334   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
335   for (unsigned N = TyInfo.size(); N; --N)
336     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
337 }
338
339 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
340 ///
341 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
342                                         std::vector<GlobalVariable *> &TyInfo) {
343   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
344   std::vector<unsigned> IdsInFilter(TyInfo.size());
345   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
346     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
347   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
348 }
349
350 /// addCleanup - Add a cleanup action for a landing pad.
351 ///
352 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
353   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
354   LP.TypeIds.push_back(0);
355 }
356
357 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
358 /// pads.
359 void MachineModuleInfo::TidyLandingPads() {
360   for (unsigned i = 0; i != LandingPads.size(); ) {
361     LandingPadInfo &LandingPad = LandingPads[i];
362     if (LandingPad.LandingPadLabel && !LandingPad.LandingPadLabel->isDefined())
363       LandingPad.LandingPadLabel = 0;
364
365     // Special case: we *should* emit LPs with null LP MBB. This indicates
366     // "nounwind" case.
367     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
368       LandingPads.erase(LandingPads.begin() + i);
369       continue;
370     }
371
372     for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
373       MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
374       MCSymbol *EndLabel = LandingPad.EndLabels[j];
375       if (BeginLabel->isDefined() && EndLabel->isDefined()) continue;
376       
377       LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
378       LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
379       --j, --e;
380     }
381
382     // Remove landing pads with no try-ranges.
383     if (LandingPads[i].BeginLabels.empty()) {
384       LandingPads.erase(LandingPads.begin() + i);
385       continue;
386     }
387
388     // If there is no landing pad, ensure that the list of typeids is empty.
389     // If the only typeid is a cleanup, this is the same as having no typeids.
390     if (!LandingPad.LandingPadBlock ||
391         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
392       LandingPad.TypeIds.clear();
393     ++i;
394   }
395 }
396
397 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is
398 /// function wide.
399 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
400   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
401     if (TypeInfos[i] == TI) return i + 1;
402
403   TypeInfos.push_back(TI);
404   return TypeInfos.size();
405 }
406
407 /// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
408 /// function wide.
409 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
410   // If the new filter coincides with the tail of an existing filter, then
411   // re-use the existing filter.  Folding filters more than this requires
412   // re-ordering filters and/or their elements - probably not worth it.
413   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
414        E = FilterEnds.end(); I != E; ++I) {
415     unsigned i = *I, j = TyIds.size();
416
417     while (i && j)
418       if (FilterIds[--i] != TyIds[--j])
419         goto try_next;
420
421     if (!j)
422       // The new filter coincides with range [i, end) of the existing filter.
423       return -(1 + i);
424
425 try_next:;
426   }
427
428   // Add the new filter.
429   int FilterID = -(1 + FilterIds.size());
430   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
431   for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
432     FilterIds.push_back(TyIds[I]);
433   FilterEnds.push_back(FilterIds.size());
434   FilterIds.push_back(0); // terminator
435   return FilterID;
436 }
437
438 /// getPersonality - Return the personality function for the current function.
439 Function *MachineModuleInfo::getPersonality() const {
440   // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
441   // function
442   return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
443 }
444
445 /// getPersonalityIndex - Return unique index for current personality
446 /// function. NULL/first personality function should always get zero index.
447 unsigned MachineModuleInfo::getPersonalityIndex() const {
448   const Function* Personality = NULL;
449
450   // Scan landing pads. If there is at least one non-NULL personality - use it.
451   for (unsigned i = 0; i != LandingPads.size(); ++i)
452     if (LandingPads[i].Personality) {
453       Personality = LandingPads[i].Personality;
454       break;
455     }
456
457   for (unsigned i = 0; i < Personalities.size(); ++i) {
458     if (Personalities[i] == Personality)
459       return i;
460   }
461
462   // This will happen if the current personality function is
463   // in the zero index.
464   return 0;
465 }
466