llvm.org GIT mirror llvm / 2b37d7c
Remove trailing whitespace git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@21416 91177308-0d34-0410-b5e6-96231b3b80d8 Misha Brukman 14 years ago
47 changed file(s) with 636 addition(s) and 636 deletion(s). Raw diff Collapse all Expand all
0 //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the generic AliasAnalysis interface which is used as the
0 //===- AliasAnalysisCounter.cpp - Alias Analysis Query Counter ------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements a pass which can be used to count how many alias queries
6666 printLine("mod/ref", MR, MRSum);
6767 std::cerr
6868 << " Mod/Ref Analysis Counter Summary: " << NoMR*100/MRSum<< "%/"
69 << JustRef*100/MRSum << "%/" << JustMod*100/MRSum << "%/"
69 << JustRef*100/MRSum << "%/" << JustMod*100/MRSum << "%/"
7070 << MR*100/MRSum <<"%\n\n";
7171 }
7272 }
9595 bool onlyReadsMemory(Function *F) {
9696 return getAnalysis().onlyReadsMemory(F);
9797 }
98
99
98
99
100100 // Forwarding functions: just delegate to a real AA implementation, counting
101101 // the number of responses...
102102 AliasResult alias(const Value *V1, unsigned V1Size,
117117 return new AliasAnalysisCounter();
118118 }
119119
120 AliasAnalysis::AliasResult
120 AliasAnalysis::AliasResult
121121 AliasAnalysisCounter::alias(const Value *V1, unsigned V1Size,
122122 const Value *V2, unsigned V2Size) {
123123 AliasResult R = getAnalysis().alias(V1, V1Size, V2, V2Size);
124
124
125125 const char *AliasString;
126126 switch (R) {
127127 default: assert(0 && "Unknown alias type!");
141141 return R;
142142 }
143143
144 AliasAnalysis::ModRefResult
144 AliasAnalysis::ModRefResult
145145 AliasAnalysisCounter::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
146146 ModRefResult R = getAnalysis().getModRefInfo(CS, P, Size);
147147
0 //===- AliasAnalysisEvaluator.cpp - Alias Analysis Accuracy Evaluator -----===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements a simple N^2 alias analysis accuracy evaluator.
5353 AU.addRequired();
5454 AU.setPreservesAll();
5555 }
56
57 bool doInitialization(Module &M) {
58 NoAlias = MayAlias = MustAlias = 0;
56
57 bool doInitialization(Module &M) {
58 NoAlias = MayAlias = MustAlias = 0;
5959 NoModRef = Mod = Ref = ModRef = 0;
6060
6161 if (PrintAll) {
6262 PrintNoAlias = PrintMayAlias = PrintMustAlias = true;
6363 PrintNoModRef = PrintMod = PrintRef = PrintModRef = true;
6464 }
65 return false;
65 return false;
6666 }
6767
6868 bool runOnFunction(Function &F);
8484 }
8585 }
8686
87 static inline void
87 static inline void
8888 PrintModRefResults(const char *Msg, bool P, Instruction *I, Value *Ptr,
8989 Module *M) {
9090 if (P) {
9898 AliasAnalysis &AA = getAnalysis();
9999
100100 const TargetData &TD = AA.getTargetData();
101
101
102102 std::set Pointers;
103103 std::set CallSites;
104104
156156 }
157157
158158 // Mod/ref alias analysis: compare all pairs of calls and values
159 for (std::set::iterator C = CallSites.begin(),
159 for (std::set::iterator C = CallSites.begin(),
160160 Ce = CallSites.end(); C != Ce; ++C) {
161161 Instruction *I = C->getInstruction();
162
162
163163 for (std::set::iterator V = Pointers.begin(), Ve = Pointers.end();
164164 V != Ve; ++V) {
165165 unsigned Size = 0;
166166 const Type *ElTy = cast((*V)->getType())->getElementType();
167167 if (ElTy->isSized()) Size = TD.getTypeSize(ElTy);
168
168
169169 switch (AA.getModRefInfo(*C, *V, Size)) {
170170 case AliasAnalysis::NoModRef:
171171 PrintModRefResults("NoModRef", PrintNoModRef, I, *V, F.getParent());
184184 }
185185 }
186186 }
187
187
188188 return false;
189189 }
190190
198198 std::cerr << "===== Alias Analysis Evaluator Report =====\n";
199199 if (AliasSum == 0) {
200200 std::cerr << " Alias Analysis Evaluator Summary: No pointers!\n";
201 } else {
201 } else {
202202 std::cerr << " " << AliasSum << " Total Alias Queries Performed\n";
203203 std::cerr << " " << NoAlias << " no alias responses ";
204204 PrintPercent(NoAlias, AliasSum);
206206 PrintPercent(MayAlias, AliasSum);
207207 std::cerr << " " << MustAlias << " must alias responses ";
208208 PrintPercent(MustAlias, AliasSum);
209 std::cerr << " Alias Analysis Evaluator Pointer Alias Summary: "
210 << NoAlias*100/AliasSum << "%/" << MayAlias*100/AliasSum << "%/"
209 std::cerr << " Alias Analysis Evaluator Pointer Alias Summary: "
210 << NoAlias*100/AliasSum << "%/" << MayAlias*100/AliasSum << "%/"
211211 << MustAlias*100/AliasSum << "%\n";
212212 }
213213
225225 PrintPercent(Ref, ModRefSum);
226226 std::cerr << " " << ModRef << " mod & ref responses ";
227227 PrintPercent(ModRef, ModRefSum);
228 std::cerr << " Alias Analysis Evaluator Mod/Ref Summary: "
229 << NoModRef*100/ModRefSum << "%/" << Mod*100/ModRefSum << "%/"
228 std::cerr << " Alias Analysis Evaluator Mod/Ref Summary: "
229 << NoModRef*100/ModRefSum << "%/" << Mod*100/ModRefSum << "%/"
230230 << Ref*100/ModRefSum << "%/" << ModRef*100/ModRefSum << "%\n";
231231 }
232232
0 //===- AliasSetTracker.cpp - Alias Sets Tracker implementation-------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the AliasSetTracker and AliasSet classes.
10 //
10 //
1111 //===----------------------------------------------------------------------===//
1212
1313 #include "llvm/Analysis/AliasSetTracker.h"
5252 CallSites.insert(CallSites.end(), AS.CallSites.begin(), AS.CallSites.end());
5353 AS.CallSites.clear();
5454 }
55
55
5656 AS.Forward = this; // Forward across AS now...
5757 addRef(); // AS is now pointing to us...
5858
505505 for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
506506 if (i) OS << ", ";
507507 WriteAsOperand(OS, CallSites[i].getCalledValue());
508 }
508 }
509509 }
510510 OS << "\n";
511511 }
0 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines the default implementation of the Alias Analysis interface
3838 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
3939 AU.addRequired();
4040 }
41
41
4242 virtual void initializePass() {
4343 TD = &getAnalysis();
4444 }
5252 std::vector *Info) {
5353 return UnknownModRefBehavior;
5454 }
55
55
5656 virtual void getArgumentAccesses(Function *F, CallSite CS,
5757 std::vector &Info) {
5858 assert(0 && "This method may not be called on this function!");
7171 virtual void deleteValue(Value *V) {}
7272 virtual void copyValue(Value *From, Value *To) {}
7373 };
74
74
7575 // Register this pass...
7676 RegisterOpt
7777 U("no-aa", "No Alias Analysis (always returns 'may' alias)");
105105
106106 virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS,
107107 std::vector *Info);
108
108
109109 private:
110110 // CheckGEPInstructions - Check two GEP instructions with known
111111 // must-aliasing base pointers. This checks to see if the index expressions
116116 const Type *BasePtr2Ty, std::vector &GEP2Ops,
117117 unsigned G2Size);
118118 };
119
119
120120 // Register this pass...
121121 RegisterOpt
122122 X("basicaa", "Basic Alias Analysis (default AA impl)");
143143
144144 // If we are at some type of object... return it.
145145 if (hasUniqueAddress(V) || isa(V)) return V;
146
146
147147 // Traverse through different addressing mechanisms...
148148 if (const Instruction *I = dyn_cast(V)) {
149149 if (isa(I) || isa(I))
306306 if (!isa(O1) && isa(V2))
307307 return NoAlias; // Unique values don't alias null
308308
309 if (isa(O1) ||
309 if (isa(O1) ||
310310 (isa(O1) &&
311311 !cast(O1)->isArrayAllocation()))
312312 if (cast(O1->getType())->getElementType()->isSized()) {
350350 do {
351351 BasePtr1 = cast(BasePtr1)->getOperand(0);
352352 } while (isGEP(BasePtr1) &&
353 cast(BasePtr1)->getOperand(1) ==
353 cast(BasePtr1)->getOperand(1) ==
354354 Constant::getNullValue(cast(BasePtr1)->getOperand(1)->getType()));
355355 do {
356356 BasePtr2 = cast(BasePtr2)->getOperand(0);
357357 } while (isGEP(BasePtr2) &&
358 cast(BasePtr2)->getOperand(1) ==
358 cast(BasePtr2)->getOperand(1) ==
359359 Constant::getNullValue(cast(BasePtr2)->getOperand(1)->getType()));
360360
361361 // Do the base pointers alias?
422422 if (ConstantFound) {
423423 if (V2Size <= 1 && V1Size <= 1) // Just pointer check?
424424 return NoAlias;
425
425
426426 // Otherwise we have to check to see that the distance is more than
427427 // the size of the argument... build an index vector that is equal to
428428 // the arguments provided, except substitute 0's for any variable
442442 }
443443 }
444444 }
445
445
446446 return MayAlias;
447447 }
448448
502502 // If so, return mustalias.
503503 if (UnequalOper == MinOperands) {
504504 if (GEP1Ops.size() < GEP2Ops.size()) std::swap(GEP1Ops, GEP2Ops);
505
505
506506 bool AllAreZeros = true;
507507 for (unsigned i = UnequalOper; i != MaxOperands; ++i)
508508 if (!isa(GEP1Ops[i]) ||
513513 if (AllAreZeros) return MustAlias;
514514 }
515515
516
516
517517 // So now we know that the indexes derived from the base pointers,
518518 // which are known to alias, are different. We can still determine a
519519 // no-alias result if there are differing constant pairs in the index
529529 for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
530530 const Value *G1Oper = GEP1Ops[FirstConstantOper];
531531 const Value *G2Oper = GEP2Ops[FirstConstantOper];
532
532
533533 if (G1Oper != G2Oper) // Found non-equal constant indexes...
534534 if (Constant *G1OC = dyn_cast(const_cast(G1Oper)))
535535 if (Constant *G2OC = dyn_cast(const_cast(G2Oper))){
554554 }
555555 BasePtr1Ty = cast(BasePtr1Ty)->getTypeAtIndex(G1Oper);
556556 }
557
557
558558 // No shared constant operands, and we ran out of common operands. At this
559559 // point, the GEP instructions have run through all of their operands, and we
560560 // haven't found evidence that there are any deltas between the GEP's.
584584 // Now crop off any constants from the end...
585585 GEP1Ops.resize(MinOperands);
586586 int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops);
587
587
588588 // If the tail provided a bit enough offset, return noalias!
589589 if ((uint64_t)(Offset2-Offset1) >= SizeMax)
590590 return NoAlias;
591591 }
592592 }
593
593
594594 // Couldn't find anything useful.
595595 return MayAlias;
596596 }
603603 // Advance BasePtr[12]Ty over this first differing constant operand.
604604 BasePtr2Ty = cast(BasePtr1Ty)->getTypeAtIndex(GEP2Ops[FirstConstantOper]);
605605 BasePtr1Ty = cast(BasePtr1Ty)->getTypeAtIndex(GEP1Ops[FirstConstantOper]);
606
606
607607 // We are going to be using TargetData::getIndexedOffset to determine the
608608 // offset that each of the GEP's is reaching. To do this, we have to convert
609609 // all variable references to constant references. To do this, we convert the
613613 GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Type::UIntTy);
614614
615615 // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
616
616
617617 // Loop over the rest of the operands...
618618 for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
619619 const Value *Op1 = i < GEP1Ops.size() ? GEP1Ops[i] : 0;
630630 if (const ArrayType *AT = dyn_cast(BasePtr1Ty))
631631 if (Op1C->getRawValue() >= AT->getNumElements())
632632 return MayAlias; // Be conservative with out-of-range accesses
633
633
634634 } else {
635635 // GEP1 is known to produce a value less than GEP2. To be
636636 // conservatively correct, we must assume the largest possible
646646 GEP1Ops[i] = ConstantSInt::get(Type::LongTy,AT->getNumElements()-1);
647647 }
648648 }
649
649
650650 if (Op2) {
651651 if (const ConstantInt *Op2C = dyn_cast(Op2)) {
652652 // If this is an array index, make sure the array element is in range.
673673 BasePtr2Ty = 0;
674674 }
675675 }
676
676
677677 if (GEPPointerTy->getElementType()->isSized()) {
678678 int64_t Offset1 = getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops);
679679 int64_t Offset2 = getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops);
680680 assert(Offset1
681681
682682 if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
683 //std::cerr << "Determined that these two GEP's don't alias ["
683 //std::cerr << "Determined that these two GEP's don't alias ["
684684 // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
685685 return NoAlias;
686686 }
705705
706706 "abs", "labs", "llabs", "imaxabs", "fabs", "fabsf", "fabsl",
707707 "trunc", "truncf", "truncl", "ldexp",
708
708
709709 "atan", "atanf", "atanl", "atan2", "atan2f", "atan2l",
710710 "cbrt",
711711 "cos", "cosf", "cosl", "cosh", "coshf", "coshl",
712 "exp", "expf", "expl",
712 "exp", "expf", "expl",
713713 "hypot",
714714 "sin", "sinf", "sinl", "sinh", "sinhf", "sinhl",
715715 "tan", "tanf", "tanl", "tanh", "tanhf", "tanhl",
722722 "iswalnum", "iswalpha", "iswcntrl", "iswdigit", "iswgraph", "iswlower",
723723 "iswprint", "iswpunct", "iswspace", "iswupper", "iswxdigit",
724724
725 "iswctype", "towctrans", "towlower", "towupper",
726
727 "btowc", "wctob",
725 "iswctype", "towctrans", "towlower", "towupper",
726
727 "btowc", "wctob",
728728
729729 "isinf", "isnan", "finite",
730730
743743
744744 static const char *OnlyReadsMemoryTable[] = {
745745 "atoi", "atol", "atof", "atoll", "atoq", "a64l",
746 "bcmp", "memcmp", "memchr", "memrchr", "wmemcmp", "wmemchr",
746 "bcmp", "memcmp", "memchr", "memrchr", "wmemcmp", "wmemchr",
747747
748748 // Strings
749749 "strcmp", "strcasecmp", "strcoll", "strncmp", "strncasecmp",
750 "strchr", "strcspn", "strlen", "strpbrk", "strrchr", "strspn", "strstr",
750 "strchr", "strcspn", "strlen", "strpbrk", "strrchr", "strspn", "strstr",
751751 "index", "rindex",
752752
753753 // Wide char strings
754754 "wcschr", "wcscmp", "wcscoll", "wcscspn", "wcslen", "wcsncmp", "wcspbrk",
755 "wcsrchr", "wcsspn", "wcsstr",
755 "wcsrchr", "wcsspn", "wcsstr",
756756
757757 // glibc
758758 "alphasort", "alphasort64", "versionsort", "versionsort64",
767767
768768 static const unsigned ORMTableSize =
769769 sizeof(OnlyReadsMemoryTable)/sizeof(OnlyReadsMemoryTable[0]);
770
771 AliasAnalysis::ModRefBehavior
770
771 AliasAnalysis::ModRefBehavior
772772 BasicAliasAnalysis::getModRefBehavior(Function *F, CallSite CS,
773773 std::vector *Info) {
774774 if (!F->isExternal()) return UnknownModRefBehavior;
788788 F->getName().c_str(), StringCompare());
789789 if (Ptr != DoesntAccessMemoryTable+DAMTableSize && *Ptr == F->getName())
790790 return DoesNotAccessMemory;
791
791
792792 Ptr = std::lower_bound(OnlyReadsMemoryTable,
793793 OnlyReadsMemoryTable+ORMTableSize,
794794 F->getName().c_str(), StringCompare());
0 //===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines a '-print-cfg' analysis pass, which emits the
9191 std::string Filename = "cfg." + F.getName() + ".dot";
9292 std::cerr << "Writing '" << Filename << "'...";
9393 std::ofstream File(Filename.c_str());
94
94
9595 if (File.good())
9696 WriteGraph(File, (const Function*)&F);
9797 else
101101 }
102102
103103 void print(std::ostream &OS, const Module* = 0) const {}
104
104
105105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106106 AU.setPreservesAll();
107107 }
119119 return false;
120120 }
121121 void print(std::ostream &OS, const Module* = 0) const {}
122
122
123123 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
124124 AU.setPreservesAll();
125125 }
139139 std::string Filename = "/tmp/cfg." + getName() + ".dot";
140140 std::cerr << "Writing '" << Filename << "'... ";
141141 std::ofstream F(Filename.c_str());
142
142
143143 if (!F.good()) {
144144 std::cerr << " error opening file for writing!\n";
145145 return;
0 //===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the BUDataStructures class, which represents the
2525 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
2626 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
2727 Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
28
28
2929 RegisterAnalysis
3030 X("budatastructure", "Bottom-up Data Structure Analysis");
3131 }
4747 GlobalValue *First = GVs[0];
4848 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
4949 GlobalECs.unionSets(First, GVs[i]);
50
50
5151 // Next, get the leader element.
5252 assert(First == GlobalECs.getLeaderValue(First) &&
5353 "First did not end up being the leader?");
54
54
5555 // Next, remove all globals from the scalar map that are not the leader.
5656 assert(GVs[0] == First && "First had to be at the front!");
5757 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
5858 ECGlobals.insert(GVs[i]);
5959 SM.erase(SM.find(GVs[i]));
6060 }
61
61
6262 // Finally, change the global node to only contain the leader.
6363 I->clearGlobals();
6464 I->addGlobal(First);
6565 }
66
66
6767 DEBUG(GG.AssertGraphOK());
6868 }
6969
160160 // nothing! In particular, externally visible globals and unresolvable call
161161 // nodes at the end of the BU phase should make things that they point to
162162 // incomplete in the globals graph.
163 //
163 //
164164 GlobalsGraph->removeTriviallyDeadNodes();
165165 GlobalsGraph->maskIncompleteMarkers();
166166
185185 if (MainFunc && !MainFunc->isExternal()) {
186186 DSGraph &MainGraph = getOrCreateGraph(MainFunc);
187187 const DSGraph &GG = *MainGraph.getGlobalsGraph();
188 ReachabilityCloner RC(MainGraph, GG,
188 ReachabilityCloner RC(MainGraph, GG,
189189 DSGraph::DontCloneCallNodes |
190190 DSGraph::DontCloneAuxCallNodes);
191191
196196 RC.getClonedNH(GG.getNodeForValue(*I));
197197
198198 MainGraph.maskIncompleteMarkers();
199 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
199 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
200200 DSGraph::IgnoreGlobals);
201201 }
202202
209209 if (Graph) return *Graph;
210210
211211 DSGraph &LocGraph = getAnalysis().getDSGraph(*F);
212
212
213213 // Steal the local graph.
214214 Graph = new DSGraph(GlobalECs, LocGraph.getTargetData());
215215 Graph->spliceFrom(LocGraph);
234234 return !callee->isExternal() || isVAHackFn(callee);
235235 }
236236
237 static void GetAllCallees(const DSCallSite &CS,
237 static void GetAllCallees(const DSCallSite &CS,
238238 std::vector &Callees) {
239239 if (CS.isDirectCall()) {
240240 if (isResolvableFunc(CS.getCalleeFunc()))
243243 // Get all callees.
244244 unsigned OldSize = Callees.size();
245245 CS.getCalleeNode()->addFullFunctionList(Callees);
246
246
247247 // If any of the callees are unresolvable, remove the whole batch!
248248 for (unsigned i = OldSize, e = Callees.size(); i != e; ++i)
249249 if (!isResolvableFunc(Callees[i])) {
264264
265265 unsigned BUDataStructures::calculateGraphs(Function *F,
266266 std::vector &Stack,
267 unsigned &NextID,
267 unsigned &NextID,
268268 hash_map &ValMap) {
269269 assert(!ValMap.count(F) && "Shouldn't revisit functions!");
270270 unsigned Min = NextID++, MyID = Min;
487487 if (!Printed)
488488 std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
489489 std::cerr << " calls " << CalledFuncs.size()
490 << " fns from site: " << CS.getCallSite().getInstruction()
490 << " fns from site: " << CS.getCallSite().getInstruction()
491491 << " " << *CS.getCallSite().getInstruction();
492492 std::cerr << " Fns =";
493493 unsigned NumPrinted = 0;
509509 if (IndCallGraph.first == 0) {
510510 std::vector::iterator I = CalledFuncs.begin(),
511511 E = CalledFuncs.end();
512
512
513513 // Start with a copy of the first graph.
514514 GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
515515 GI->setGlobalsGraph(Graph.getGlobalsGraph());
538538 for (e = NextArgs.size(); i != e; ++i)
539539 Args.push_back(NextArgs[i]);
540540 }
541
541
542542 // Clean up the final graph!
543543 GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
544544 } else {
579579 // Clone everything reachable from globals in the function graph into the
580580 // globals graph.
581581 for (DSScalarMap::global_iterator I = MainSM.global_begin(),
582 E = MainSM.global_end(); I != E; ++I)
582 E = MainSM.global_end(); I != E; ++I)
583583 RC.getClonedNH(MainSM[*I]);
584584
585585 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
0 //===- CompleteBottomUp.cpp - Complete Bottom-Up Data Structure Graphs ----===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This is the exact same as the bottom-up graphs, but we use take a completed
5151 } else {
5252 std::cerr << "CBU-DSA: No 'main' function found!\n";
5353 }
54
54
5555 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
5656 if (!I->isExternal() && !DSInfo.count(I))
5757 calculateSCCGraphs(getOrCreateGraph(*I), Stack, NextID, ValMap);
6565 if (MainFunc && !MainFunc->isExternal()) {
6666 DSGraph &MainGraph = getOrCreateGraph(*MainFunc);
6767 const DSGraph &GG = *MainGraph.getGlobalsGraph();
68 ReachabilityCloner RC(MainGraph, GG,
68 ReachabilityCloner RC(MainGraph, GG,
6969 DSGraph::DontCloneCallNodes |
7070 DSGraph::DontCloneAuxCallNodes);
7171
7676 RC.getClonedNH(GG.getNodeForValue(*I));
7777
7878 MainGraph.maskIncompleteMarkers();
79 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
79 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
8080 DSGraph::IgnoreGlobals);
8181 }
8282
106106
107107 unsigned CompleteBUDataStructures::calculateSCCGraphs(DSGraph &FG,
108108 std::vector &Stack,
109 unsigned &NextID,
109 unsigned &NextID,
110110 hash_map &ValMap) {
111111 assert(!ValMap.count(&FG) && "Shouldn't revisit functions!");
112112 unsigned Min = NextID++, MyID = Min;
156156 // Remove NG from the ValMap since the pointer may get recycled.
157157 ValMap.erase(NG);
158158 delete NG;
159
159
160160 Stack.pop_back();
161161 IsMultiNodeSCC = true;
162162 }
164164 // Clean up the graph before we start inlining a bunch again...
165165 if (IsMultiNodeSCC)
166166 FG.removeTriviallyDeadNodes();
167
167
168168 Stack.pop_back();
169169 processGraph(FG);
170170 ValMap[&FG] = ~0U;
186186
187187 assert(calls.insert(TheCall).second &&
188188 "Call instruction occurs multiple times in graph??");
189
189
190190 // Fast path for noop calls. Note that we don't care about merging globals
191191 // in the callee with nodes in the caller here.
192192 if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0)
195195 // Loop over all of the potentially called functions...
196196 // Inline direct calls as well as indirect calls because the direct
197197 // callee may have indirect callees and so may have changed.
198 //
198 //
199199 callee_iterator I = callee_begin(TheCall),E = callee_end(TheCall);
200200 unsigned TNum = 0, Num = 0;
201201 DEBUG(Num = std::distance(I, E));
207207 // calls or for self recursion within an SCC.
208208 DSGraph &GI = getOrCreateGraph(*CalleeFunc);
209209 ++NumCBUInlines;
210 G.mergeInGraph(CS, *CalleeFunc, GI,
210 G.mergeInGraph(CS, *CalleeFunc, GI,
211211 DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes |
212212 DSGraph::DontCloneAuxCallNodes);
213213 DEBUG(std::cerr << " Inlining graph [" << i << "/"
0 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the core data structure functionality.
9494 return I->second;
9595 }
9696 }
97
97
9898 // Okay, this is either not an equivalenced global or it is the leader, it
9999 // will be inserted into the scalar map now.
100100 GlobalSet.insert(GV);
162162 Ty = Type::VoidTy;
163163
164164 // Remove this node from the parent graph's Nodes list.
165 ParentGraph->unlinkNode(this);
165 ParentGraph->unlinkNode(this);
166166 ParentGraph = 0;
167167 }
168168
220220 DestNode->Ty = Type::VoidTy;
221221 DestNode->Size = 1;
222222 DestNode->Globals.swap(Globals);
223
223
224224 // Start forwarding to the destination node...
225225 forwardNode(DestNode, 0);
226
226
227227 if (!Links.empty()) {
228228 DestNode->Links.reserve(1);
229
229
230230 DSNodeHandle NH(DestNode);
231231 DestNode->Links.push_back(Links[0]);
232
232
233233 // If we have links, merge all of our outgoing links together...
234234 for (unsigned i = Links.size()-1; i != 0; --i)
235235 NH.getNode()->Links[0].mergeWith(Links[i]);
327327 ++SS.Idx;
328328 if (SS.Idx != ST->getNumElements()) {
329329 const StructLayout *SL = TD.getStructLayout(ST);
330 SS.Offset +=
330 SS.Offset +=
331331 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
332332 return;
333333 }
387387 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
388388 bool AllowLargerT1, const TargetData &TD){
389389 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
390
390
391391 while (!T1W.isDone() && !T2W.isDone()) {
392392 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
393393 return false;
396396 const Type *T2 = T2W.getCurrentType();
397397 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
398398 return false;
399
399
400400 T1W.StepToNextType();
401401 T2W.StepToNextType();
402402 }
403
403
404404 return AllowLargerT1 || T1W.isDone();
405405 }
406406
572572 if (isa(SubType) &&
573573 isa(NewTy)) return false;
574574
575 unsigned SubTypeSize = SubType->isSized() ?
575 unsigned SubTypeSize = SubType->isSized() ?
576576 (unsigned)TD.getTypeSize(SubType) : 0;
577577
578578 // Ok, we are getting desperate now. Check for physical subtyping, where we
579579 // just require each element in the node to be compatible.
580580 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
581 SubTypeSize && SubTypeSize < 256 &&
581 SubTypeSize && SubTypeSize < 256 &&
582582 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
583583 return false;
584584
610610 NextPadSize = NextSubTypeSize;
611611 break;
612612 default: ;
613 // fall out
613 // fall out
614614 }
615615
616616 if (NextSubType == 0)
706706 } else {
707707 // Make a copy to the side of Dest...
708708 std::vector Old(Dest);
709
709
710710 // Make space for all of the type entries now...
711711 Dest.resize(Dest.size()+Src.size());
712
712
713713 // Merge the two sorted ranges together... into Dest.
714714 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
715
716 // Now erase any duplicate entries that may have accumulated into the
715
716 // Now erase any duplicate entries that may have accumulated into the
717717 // vectors (because they were in both of the input sets)
718718 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
719719 }
727727 // This function does the hard work of merging two nodes, CurNodeH
728728 // and NH after filtering out trivial cases and making sure that
729729 // CurNodeH.offset >= NH.offset.
730 //
730 //
731731 // ***WARNING***
732732 // Since merging may cause either node to go away, we must always
733733 // use the node-handles to refer to the nodes. These node handles are
760760 #endif
761761 }
762762
763 // Merge the type entries of the two nodes together...
763 // Merge the type entries of the two nodes together...
764764 if (NH.getNode()->Ty != Type::VoidTy)
765765 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
766766 assert(!CurNodeH.getNode()->isDeadNode());
915915 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
916916 DN->maskNodeTypes(BitsToKeep);
917917 NH = DN;
918
918
919919 // Next, recursively clone all outgoing links as necessary. Note that
920920 // adding these links can cause the node to collapse itself at any time, and
921921 // the current node may be merged with arbitrary other nodes. For this
938938 CN->addEdgeTo(MergeOffset, DestEdge);
939939 }
940940 }
941
941
942942 // If this node contains any globals, make sure they end up in the scalar
943943 // map with the correct offset.
944944 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
976976 SCNH.getOffset()+SrcNH.getOffset()));
977977 return; // Nothing to do!
978978 }
979
979
980980 // Okay, so the source node has not already been cloned. Instead of creating
981981 // a new DSNode, only to merge it into the one we already have, try to perform
982982 // the merge in-place. The only case we cannot handle here is when the offset
10051005 }
10061006 #endif
10071007 }
1008
1009 // Merge the type entries of the two nodes together...
1008
1009 // Merge the type entries of the two nodes together...
10101010 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
10111011 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
10121012 DN = NH.getNode();
10141014 }
10151015
10161016 assert(!DN->isDeadNode());
1017
1017
10181018 // Merge the NodeType information.
10191019 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
10201020
10591059 // sure it is known that this is the representative node for the src node.
10601060 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
10611061
1062 // If the source node contained any globals, make sure to create entries
1062 // If the source node contained any globals, make sure to create entries
10631063 // in the scalar map for them!
10641064 for (DSNode::globals_iterator I = SN->globals_begin(),
10651065 E = SN->globals_end(); I != E; ++I) {
10911091 DSNode *CN = SCNH.getNode();
10921092 unsigned MergeOffset =
10931093 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
1094
1094
10951095 DSNodeHandle Tmp = CN->getLink(MergeOffset);
10961096 if (!Tmp.isNull()) {
10971097 // Perform the recursive merging. Make sure to create a temporary NH,
11191119 merge(DestCS.getRetVal(), SrcCS.getRetVal());
11201120 unsigned MinArgs = DestCS.getNumPtrArgs();
11211121 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1122
1122
11231123 for (unsigned a = 0; a != MinArgs; ++a)
11241124 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
11251125
12521252 New->maskNodeTypes(~BitsToClear);
12531253 OldNodeMap[I] = New;
12541254 }
1255
1255
12561256 #ifndef NDEBUG
12571257 Timer::addPeakMemoryMeasurement();
12581258 #endif
1259
1259
12601260 // Rewrite the links in the new nodes to point into the current graph now.
12611261 // Note that we don't loop over the node's list to do this. The problem is
12621262 // that remaping links can cause recursive merging to happen, which means
13131313 I->setParentGraph(this);
13141314 // Take all of the nodes.
13151315 Nodes.splice(Nodes.end(), RHS.Nodes);
1316
1316
13171317 // Take all of the calls.
13181318 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
13191319 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
13751375 unsigned CurNodeId;
13761376 std::vector SCCStack;
13771377 std::map > NodeInfo;
1378
1378
13791379 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
13801380 // Remove null pointer as a special case.
13811381 NodeInfo[0] = std::make_pair(0, false);
14721472 /// call site (in this graph) with the bindings specified by the vector in G2.
14731473 /// The two DSGraphs must be different.
14741474 ///
1475 void DSGraph::mergeInGraph(const DSCallSite &CS,
1475 void DSGraph::mergeInGraph(const DSCallSite &CS,
14761476 std::vector &Args,
14771477 const DSGraph &Graph, unsigned CloneFlags) {
14781478 TIME_REGION(X, "mergeInGraph");
14841484 if (&Graph == this) {
14851485 // Merge the return value with the return value of the context.
14861486 Args[0].mergeWith(CS.getRetVal());
1487
1487
14881488 // Resolve all of the function arguments.
14891489 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
14901490 if (i == Args.size()-1)
14911491 break;
1492
1492
14931493 // Add the link from the argument scalar to the provided value.
14941494 Args[i+1].mergeWith(CS.getPtrArg(i));
14951495 }
15001500 // scalars in the old graph _used_ to point, and of the new nodes matching
15011501 // nodes of the old graph.
15021502 ReachabilityCloner RC(*this, Graph, CloneFlags);
1503
1503
15041504 // Map the return node pointer over.
15051505 if (!CS.getRetVal().isNull())
15061506 RC.merge(CS.getRetVal(), Args[0]);
15091509 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
15101510 if (i == Args.size()-1)
15111511 break;
1512
1512
15131513 // Add the link from the argument scalar to the provided value.
15141514 RC.merge(CS.getPtrArg(i), Args[i+1]);
15151515 }
1516
1516
15171517 // We generally don't want to copy global nodes or aux calls from the callee
15181518 // graph to the caller graph. However, we have to copy them if there is a
15191519 // path from the node to a node we have already copied which does not go
15471547 // Copy aux calls that are needed.
15481548 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
15491549 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
1550
1550
15511551 // Copy globals that are needed.
15521552 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
15531553 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
17581758 killIfUselessEdge(CS.getRetVal());
17591759 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
17601760 killIfUselessEdge(CS.getPtrArg(a));
1761
1761
17621762 #if 0
17631763 // If this call site calls the same function as the last call site, and if
17641764 // the function pointer contains an external function, this node will
17751775 else
17761776 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
17771777 }
1778
1778
17791779 // It is not clear why, but enabling this code makes DSA really
17801780 // sensitive to node forwarding. Basically, with this enabled, DSA
17811781 // performs different number of inlinings based on which nodes are
17901790 NumDuplicateCalls > 20
17911791 #endif
17921792 ) {
1793
1793
17941794 std::list::iterator PrevIt = OldIt;
17951795 --PrevIt;
17961796 PrevIt->mergeWith(CS);
1797
1797
17981798 // No need to keep this call anymore.
17991799 Calls.erase(OldIt);
18001800 ++NumDeleted;
19561956 void DSCallSite::markReachableNodes(hash_set &Nodes) const {
19571957 getRetVal().getNode()->markReachableNodes(Nodes);
19581958 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1959
1959
19601960 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
19611961 getPtrArg(i).getNode()->markReachableNodes(Nodes);
19621962 }
20542054
20552055 // Make sure that all globals are cloned over as roots.
20562056 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
2057 DSGraph::ScalarMapTy::iterator SMI =
2057 DSGraph::ScalarMapTy::iterator SMI =
20582058 GlobalsGraph->getScalarMap().find(I->first);
20592059 if (SMI != GlobalsGraph->getScalarMap().end())
20602060 GGCloner.merge(SMI->second, I->second);
20782078
20792079 // Now find globals and aux call nodes that are already live or reach a live
20802080 // value (which makes them live in turn), and continue till no more are found.
2081 //
2081 //
20822082 bool Iterate;
20832083 hash_set Visited;
20842084 hash_set AuxFCallsAlive;
20912091 Iterate = false;
20922092 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
20932093 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
2094 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
2094 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
20952095 Flags & DSGraph::RemoveUnreachableGlobals)) {
20962096 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
20972097 GlobalNodes.pop_back(); // erase efficiently
21232123 // Copy and merge global nodes and dead aux call nodes into the
21242124 // GlobalsGraph, and all nodes reachable from those nodes. Update their
21252125 // target pointers using the GGCloner.
2126 //
2126 //
21272127 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
21282128 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
21292129
21792179 #if 0
21802180 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
21812181 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2182 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
2182 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
21832183 #endif
21842184 }
21852185 AssertNodeInGraph(CS.getRetVal().getNode());
22492249 }
22502250 return;
22512251 }
2252
2252
22532253 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
22542254
22552255 // Loop over all of the fields that N1 and N2 have in common, recursively
22832283 E = SM.global_end(); I != E; ++I)
22842284 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
22852285 }
2286
2286
22872287 /// computeGGToGMapping - Compute the mapping of nodes in the global graph to
22882288 /// nodes in this graph. Note that any uses of this method are probably bugs,
22892289 /// unless it is known that the globals graph has been merged into this graph!
22972297 NodeMap.erase(NodeMap.begin());
22982298 }
22992299 }
2300
2300
23012301
23022302 /// computeCalleeCallerMapping - Given a call from a function in the current
23032303 /// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
23082308
23092309 DSCallSite CalleeArgs =
23102310 CalleeGraph.getCallSiteForArguments(const_cast(Callee));
2311
2311
23122312 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
23132313
23142314 unsigned NumArgs = CS.getNumPtrArgs();
23172317
23182318 for (unsigned i = 0; i != NumArgs; ++i)
23192319 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2320
2320
23212321 // Map the nodes that are pointed to by globals.
23222322 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
23232323 DSScalarMap &CallerSM = getScalarMap();
23242324
23252325 if (CalleeSM.global_size() >= CallerSM.global_size()) {
2326 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
2326 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
23272327 E = CallerSM.global_end(); GI != E; ++GI)
23282328 if (CalleeSM.global_count(*GI))
23292329 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
23302330 } else {
2331 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
2331 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
23322332 E = CalleeSM.global_end(); GI != E; ++GI)
23332333 if (CallerSM.global_count(*GI))
23342334 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
0 //===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass uses the top-down data structure graphs to implement a simple
6767
6868 //------------------------------------------------
6969 // Implement the AliasAnalysis API
70 //
70 //
7171
7272 AliasResult alias(const Value *V1, unsigned V1Size,
7373 const Value *V2, unsigned V2Size);
123123 DSGraph *G1 = getGraphForValue(V1);
124124 DSGraph *G2 = getGraphForValue(V2);
125125 assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?");
126
126
127127 // Get the graph to use...
128128 DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph()));
129129
130130 const DSGraph::ScalarMapTy &GSM = G.getScalarMap();
131131 DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1);
132132 if (I == GSM.end()) return NoAlias;
133
133
134134 DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2);
135135 if (J == GSM.end()) return NoAlias;
136136
187187
188188 HaveMappingInfo:
189189 assert(N && "Null pointer in scalar map??");
190
190
191191 typedef std::multimap::iterator NodeMapIt;
192192 std::pair Range = CallerCalleeMap.equal_range(N);
193
193
194194 // Loop over all of the nodes in the callee that correspond to "N", keeping
195195 // track of aggregate mod/ref info.
196196 bool NeverReads = true, NeverWrites = true;
202202 if (NeverReads == false && NeverWrites == false)
203203 return AliasAnalysis::getModRefInfo(CS, P, Size);
204204 }
205
205
206206 ModRefResult Result = ModRef;
207207 if (NeverWrites) // We proved it was not modified.
208208 Result = ModRefResult(Result & ~Mod);
209209 if (NeverReads) // We proved it was not read.
210210 Result = ModRefResult(Result & ~Ref);
211
211
212212 return ModRefResult(Result & AliasAnalysis::getModRefInfo(CS, P, Size));
213213 }
214214
0 //===- DataStructureOpt.cpp - Data Structure Analysis Based Optimizations -===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass uses DSA to a series of simple optimizations, like marking
6565 DSNode *GNode = 0;
6666 DSGraph::ScalarMapTy::const_iterator SMI = SM.find(I);
6767 if (SMI != SM.end()) GNode = SMI->second.getNode();
68
68
6969 if (GNode == 0 && I->hasInternalLinkage()) {
7070 // If there is no entry in the scalar map for this global, it was never
7171 // referenced in the program. If it has internal linkage, that means we
0 //===- DataStructureStats.cpp - Various statistics for DS Graphs ----------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines a little pass that prints out statistics for DS Graphs.
7575 unsigned numIndirectCalls = 0, totalNumCallees = 0;
7676
7777 for (DSGraph::fc_iterator I = TDGraph->fc_begin(), E = TDGraph->fc_end();
78 I != E; ++I)
78 I != E; ++I)
7979 if (isIndirectCallee(I->getCallSite().getCalledValue())) {
8080 // This is an indirect function call
8181 std::vector Callees;
8989 << "' at call: \n"
9090 << *I->getCallSite().getInstruction();
9191 }
92
92
9393 TotalNumCallees += totalNumCallees;
9494 NumIndirectCalls += numIndirectCalls;
95
95
9696 if (numIndirectCalls)
9797 std::cout << " In function " << F.getName() << ": "
9898 << (totalNumCallees / (double) numIndirectCalls)
0 //===- EquivClassGraphs.cpp - Merge equiv-class graphs & inline bottom-up -===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass is the same as the complete bottom-up graphs, but
4949
5050 DSGraph::NodeMapTy GlobalsGraphNodeMapping;
5151 G.computeGToGGMapping(GlobalsGraphNodeMapping);
52 }
52 }
5353 }
5454 #endif
5555
5656 // getSomeCalleeForCallSite - Return any one callee function at a call site.
57 //
57 //
5858 Function *EquivClassGraphs::getSomeCalleeForCallSite(const CallSite &CS) const{
5959 Function *thisFunc = CS.getCaller();
6060 assert(thisFunc && "getSomeCalleeForCallSite(): Not a valid call site?");
9393 } else {
9494 std::cerr << "Fold Graphs: No 'main' function found!\n";
9595 }
96
96
9797 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
9898 if (!I->isExternal())
9999 processSCC(getOrCreateGraph(*I), Stack, NextID, ValMap);
109109 if (MainFunc && !MainFunc->isExternal()) {
110110 DSGraph &MainGraph = getOrCreateGraph(*MainFunc);
111111 const DSGraph &GG = *MainGraph.getGlobalsGraph();
112 ReachabilityCloner RC(MainGraph, GG,
112 ReachabilityCloner RC(MainGraph, GG,
113113 DSGraph::DontCloneCallNodes |
114114 DSGraph::DontCloneAuxCallNodes);
115115
120120 RC.getClonedNH(GG.getNodeForValue(*I));
121121
122122 MainGraph.maskIncompleteMarkers();
123 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
123 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
124124 DSGraph::IgnoreGlobals);
125125 }
126126
157157 //
158158 void EquivClassGraphs::buildIndirectFunctionSets(Module &M) {
159159 const ActualCalleesTy& AC = CBU->getActualCallees();
160
160
161161 // Loop over all of the indirect calls in the program. If a call site can
162162 // call multiple different functions, we need to unify all of the callees into
163163 // the same equivalence class.
203203 // equivalence class. More precisely, if F is in the class, and G(F) is
204204 // its graph, then we include all other functions that are also in G(F).
205205 // Currently, that is just the functions in the same call-graph-SCC as F.
206 //
206 //
207207 DSGraph& funcDSGraph = CBU->getDSGraph(*I->second);
208208 for (DSGraph::retnodes_iterator RI = funcDSGraph.retnodes_begin(),
209209 RE = funcDSGraph.retnodes_end(); RI != RE; ++RI)
241241 DSGraph &MergedG = getOrCreateGraph(*LF);
242242
243243 // Record the argument nodes for use in merging later below.
244 std::vector ArgNodes;
244 std::vector ArgNodes;
245245
246246 for (Function::arg_iterator AI = LF->arg_begin(), E = LF->arg_end();
247247 AI != E; ++AI)
248248 if (DS::isPointerType(AI->getType()))
249249 ArgNodes.push_back(MergedG.getNodeForValue(AI));
250
250
251251 // Merge in the graphs of all other functions in this equiv. class. Note
252252 // that two or more functions may have the same graph, and it only needs
253253 // to be merged in once.
254254 std::set GraphsMerged;
255255 GraphsMerged.insert(&CBU->getDSGraph(*LF));
256
256
257257 for (++SI; SI != FuncECs.member_end(); ++SI) {
258258 Function *F = *SI;
259259 DSGraph *&FG = DSInfo[F];
260
261 DSGraph &CBUGraph = CBU->getDSGraph(*F);
260
261 DSGraph &CBUGraph = CBU->getDSGraph(*F);
262262 if (GraphsMerged.insert(&CBUGraph).second) {
263263 // Record the "folded" graph for the function.
264264 for (DSGraph::retnodes_iterator I = CBUGraph.retnodes_begin(),
266266 assert(DSInfo[I->first] == 0 && "Graph already exists for Fn!");
267267 DSInfo[I->first] = &MergedG;
268268 }
269
269
270270 // Clone this member of the equivalence class into MergedG.
271271 MergedG.cloneInto(CBUGraph);
272272 }
273
273
274274 // Merge the return nodes of all functions together.
275275 MergedG.getReturnNodes()[LF].mergeWith(MergedG.getReturnNodes()[F]);
276
276
277277 // Merge the function arguments with all argument nodes found so far.
278278 // If there are extra function args, add them to the vector of argNodes
279279 Function::arg_iterator AI2 = F->arg_begin(), AI2end = F->arg_end();
281281 arg != numArgs && AI2 != AI2end; ++AI2, ++arg)
282282 if (DS::isPointerType(AI2->getType()))
283283 ArgNodes[arg].mergeWith(MergedG.getNodeForValue(AI2));
284
284
285285 for ( ; AI2 != AI2end; ++AI2)
286286 if (DS::isPointerType(AI2->getType()))
287287 ArgNodes.push_back(MergedG.getNodeForValue(AI2));
318318
319319
320320 unsigned EquivClassGraphs::
321 processSCC(DSGraph &FG, std::vector &Stack, unsigned &NextID,
321 processSCC(DSGraph &FG, std::vector &Stack, unsigned &NextID,
322322 std::map &ValMap) {
323323 std::map::iterator It = ValMap.lower_bound(&FG);
324324 if (It != ValMap.end() && It->first == &FG)
365365 for (DSGraph::retnodes_iterator I = NG->retnodes_begin();
366366 I != NG->retnodes_end(); ++I)
367367 DSInfo[I->first] = &FG;
368
368
369369 // Remove NG from the ValMap since the pointer may get recycled.
370370 ValMap.erase(NG);
371371 delete NG;
403403
404404 assert(calls.insert(TheCall).second &&
405405 "Call instruction occurs multiple times in graph??");
406
406
407407 if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0)
408408 continue;
409409
410410 // Inline the common callee graph into the current graph, if the callee
411411 // graph has not changed. Note that all callees should have the same
412412 // graph so we only need to do this once.
413 //
413 //
414414 DSGraph* CalleeGraph = NULL;
415415 callee_iterator I = callee_begin(TheCall), E = callee_end(TheCall);
416416 unsigned TNum, Num;
423423 // Now check if the graph has changed and if so, clone and inline it.
424424 if (I != E) {
425425 Function *CalleeFunc = I->second;
426
426
427427 // Merge the callee's graph into this graph, if not already the same.
428428 // Callees in the same equivalence class (which subsumes those
429429 // in the same SCCs) have the same graph. Note that all recursion
430430 // including self-recursion have been folded in the equiv classes.
431 //
431 //
432432 CalleeGraph = &getOrCreateGraph(*CalleeFunc);
433433 if (CalleeGraph != &G) {
434434 ++NumFoldGraphInlines;
462462 // Recompute the Incomplete markers.
463463 G.maskIncompleteMarkers();
464464 G.markIncompleteNodes(DSGraph::MarkFormalArgs);
465
465
466466 // Delete dead nodes. Treat globals that are unreachable but that can
467467 // reach live nodes as live.
468468 G.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
475475 // globals graph.
476476 DSScalarMap &MainSM = G.getScalarMap();
477477 for (DSScalarMap::global_iterator I = MainSM.global_begin(),
478 E = MainSM.global_end(); I != E; ++I)
478 E = MainSM.global_end(); I != E; ++I)
479479 RC.getClonedNH(MainSM[*I]);
480480
481481 DEBUG(std::cerr << " -- DONE ProcessGraph for function "
0 //===- GraphChecker.cpp - Assert that various graph properties hold -------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass is used to test DSA with regression tests. It can be used to check
3838 cl::desc("Specify which DSA pass the -datastructure-gc pass should use"),
3939 cl::values(clEnumVal(local, "Local pass"),
4040 clEnumVal(bu, "Bottom-up pass"),
41 clEnumVal(td, "Top-down pass"),
41 clEnumVal(td, "Top-down pass"),
4242 clEnumValEnd), cl::init(local));
4343
4444 cl::opt
132132 std::set AbortIfMergedS(AbortIfMerged.begin(),
133133 AbortIfMerged.end());
134134 std::map CheckFlagsM;
135
135
136136 for (cl::list::iterator I = CheckFlags.begin(),
137137 E = CheckFlags.end(); I != E; ++I) {
138138 std::string::size_type ColonPos = I->rfind(':');
157157 }
158158 CheckFlagsM[std::string(I->begin(), I->begin()+ColonPos)] = Flags;
159159 }
160
160
161161 // Now we loop over all of the scalars, checking to see if any are collapsed
162162 // that are not supposed to be, or if any are merged together.
163163 const DSGraph::ScalarMapTy &SM = G.getScalarMap();
164164 std::map AbortIfMergedNodes;
165
165
166166 for (DSGraph::ScalarMapTy::const_iterator I = SM.begin(), E = SM.end();
167167 I != E; ++I)
168168 if (I->first->hasName() && I->second.getNode()) {
169169 const std::string &Name = I->first->getName();
170170 DSNode *N = I->second.getNode();
171
171
172172 // Verify it is not collapsed if it is not supposed to be...
173173 if (N->isNodeCompletelyFolded() && AbortIfCollapsedS.count(Name)) {
174174 std::cerr << "Node for value '%" << Name << "' is collapsed: ";
0 //===- Local.cpp - Compute a local data structure graph for a function ----===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // Compute the local version of the data structure graph for a function. The
7575 std::list *FunctionCalls;
7676
7777 public:
78 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
78 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
7979 std::list &fc)
8080 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
8181 FunctionCalls(&fc) {
147147 ///
148148 void setDestTo(Value &V, const DSNodeHandle &NH);
149149
150 /// getValueDest - Return the DSNode that the actual value points to.
150 /// getValueDest - Return the DSNode that the actual value points to.
151151 ///
152152 DSNodeHandle getValueDest(Value &V);
153153
181181 // initializers into the local graph from the globals graph.
182182 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
183183 ReachabilityCloner RC(*this, *GG, 0);
184
184
185185 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
186186 I != ScalarMap.global_end(); ++I)
187187 if (GlobalVariable *GV = dyn_cast(*I))
312312
313313 void GraphBuilder::visitSelectInst(SelectInst &SI) {
314314 if (!isPointerType(SI.getType())) return; // Only pointer Selects
315
315
316316 DSNodeHandle &Dest = ScalarMap[&SI];
317317 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
318318 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
572572 AI != E; ++AI) {
573573 if (isPointerType((*AI)->getType()))
574574 if (DSNode *N = getValueDest(**AI).getNode())
575 N->setReadMarker();
575 N->setReadMarker();
576576 }
577577 return;
578578 } else if (F->getName() == "read" || F->getName() == "pipe" ||
582582 AI != E; ++AI) {
583583 if (isPointerType((*AI)->getType()))
584584 if (DSNode *N = getValueDest(**AI).getNode())
585 N->setModifiedMarker();
585 N->setModifiedMarker();
586586 }
587587 return;
588588 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
629629 if (isPointerType((*AI)->getType()))
630630 if (DSNode *N = getValueDest(**AI).getNode())
631631 N->setReadMarker();
632
632
633633 // fopen allocates in an unknown way and writes to the file
634634 // descriptor. Also, merge the allocated type into the node.
635635 DSNodeHandle Result = getValueDest(*CS.getInstruction());
660660 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
661661 }
662662 return;
663 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
663 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
664664 (F->getName() == "fflush" || F->getName() == "feof" ||
665665 F->getName() == "fileno" || F->getName() == "clearerr" ||
666666 F->getName() == "rewind" || F->getName() == "ftell" ||
671671 DSNodeHandle H = getValueDest(**CS.arg_begin());
672672 if (DSNode *N = H.getNode()) {
673673 N->setReadMarker()->setModifiedMarker();
674
674
675675 const Type *ArgTy = F->getFunctionType()->getParamType(0);
676676 if (const PointerType *PTy = dyn_cast(ArgTy))
677677 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
678678 }
679679 return;
680 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
680 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
681681 (F->getName() == "fwrite" || F->getName() == "fread")) {
682682 // fread writes the first operand, fwrite reads it. They both
683683 // read/write the FILE descriptor, and merges the FILE type.
738738 AI != E; ++AI)
739739 if (isPointerType((*AI)->getType()))
740740 if (DSNode *N = getValueDest(**AI).getNode())
741 N->setReadMarker();
741 N->setReadMarker();
742742 return;
743743 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
744744 F->getName() == "fsetpos") {
788788 // printf reads all pointer arguments.
789789 if (isPointerType((*AI)->getType()))
790790 if (DSNode *N = getValueDest(**AI).getNode())
791 N->setReadMarker();
791 N->setReadMarker();
792792 }
793793 return;
794794 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
824824 N->setReadMarker();
825825 ++AI;
826826 }
827
827
828828 // Read the valist, and the pointed-to objects.
829829 if (AI != E && isPointerType((*AI)->getType())) {
830830 const DSNodeHandle &VAList = getValueDest(**AI);
868868 // scanf writes all pointer arguments.
869869 if (isPointerType((*AI)->getType()))
870870 if (DSNode *N = getValueDest(**AI).getNode())
871 N->setModifiedMarker();
871 N->setModifiedMarker();
872872 }
873873 return;
874874 } else if (F->getName() == "strtok") {
904904 if (isPointerType((*AI)->getType()))
905905 if (DSNode *N = getValueDest(**AI).getNode())
906906 N->setReadMarker();
907
907
908908 if (DSNode *N = H.getNode())
909909 N->setReadMarker();
910910 return;
10781078 GlobalValue *First = GVs[0];
10791079 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
10801080 GlobalECs.unionSets(First, GVs[i]);
1081
1081
10821082 // Next, get the leader element.
10831083 assert(First == GlobalECs.getLeaderValue(First) &&
10841084 "First did not end up being the leader?");
1085
1085
10861086 // Next, remove all globals from the scalar map that are not the leader.
10871087 assert(GVs[0] == First && "First had to be at the front!");
10881088 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
10891089 ECGlobals.insert(GVs[i]);
10901090 SM.erase(SM.find(GVs[i]));
10911091 }
1092
1092
10931093 // Finally, change the global node to only contain the leader.
10941094 I->clearGlobals();
10951095 I->addGlobal(First);
10961096 }
1097
1097
10981098 DEBUG(GG.AssertGraphOK());
10991099 }
11001100
11501150 GlobalsGraph = new DSGraph(GlobalECs, TD);
11511151 {
11521152 GraphBuilder GGB(*GlobalsGraph);
1153
1153
11541154 // Add initializers for all of the globals to the globals graph.
11551155 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
11561156 I != E; ++I)
0 //===- Printer.cpp - Code for printing data structure graphs nicely -------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the 'dot' graph printer.
7575
7676 EquivalenceClasses *GlobalECs = 0;
7777 if (G) GlobalECs = &G->getGlobalECs();
78
78
7979 for (unsigned i = 0, e = N->getGlobalsList().size(); i != e; ++i) {
8080 WriteAsOperand(OS, N->getGlobalsList()[i], false, true, M);
8181
8484 EquivalenceClasses::iterator I =
8585 GlobalECs->findValue(N->getGlobalsList()[i]);
8686 if (I != GlobalECs->end()) {
87 unsigned NumMembers =
87 unsigned NumMembers =
8888 std::distance(GlobalECs->member_begin(I), GlobalECs->member_end());
8989 if (NumMembers != 1) OS << " + " << (NumMembers-1) << " EC";
9090 }
131131 return R;
132132 }
133133
134
134
135135 /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
136136 /// and the return node.
137137 ///
155155 std::stringstream OS;
156156 WriteAsOperand(OS, I->first, false, true, CurMod);
157157 GW.emitSimpleNode(I->first, "", OS.str());
158
158
159159 // Add edge from return node to real destination
160160 DSNode *DestNode = I->second.getNode();
161161 int EdgeDest = I->second.getOffset() >> DS::PointerShift;
240240 std::string Filename = GraphName + ".dot";
241241 O << "Writing '" << Filename << "'...";
242242 std::ofstream F(Filename.c_str());
243
243
244244 if (F.good()) {
245245 print(F);
246246 unsigned NumCalls = shouldPrintAuxCalls() ?
328328 << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
329329 }
330330
331 O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes
331 O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes
332332 << "] nodes total" << std::endl;
333333 }
334334
0 //===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass uses the data structure graphs to implement a simple context
5858
5959 //------------------------------------------------
6060 // Implement the AliasAnalysis API
61 //
61 //
6262
6363 AliasResult alias(const Value *V1, unsigned V1Size,
6464 const Value *V2, unsigned V2Size);
139139 for (std::list::iterator CI = Calls.begin(), E = Calls.end();
140140 CI != E;) {
141141 DSCallSite &CurCall = *CI++;
142
142
143143 // Loop over the called functions, eliminating as many as possible...
144144 std::vector CallTargets;
145145 if (CurCall.isDirectCall())
146146 CallTargets.push_back(CurCall.getCalleeFunc());
147 else
147 else
148148 CurCall.getCalleeNode()->addFullFunctionList(CallTargets);
149149
150150 for (unsigned c = 0; c != CallTargets.size(); ) {
238238 AliasAnalysis::ModRefResult
239239 Steens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
240240 AliasAnalysis::ModRefResult Result = ModRef;
241
241
242242 // Find the node in question.
243243 DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
244244 DSGraph::ScalarMapTy::iterator I = GSM.find(P);
245
245
246246 if (I != GSM.end() && !I->second.isNull()) {
247247 DSNode *N = I->second.getNode();
248248 if (N->isComplete()) {
252252 if (Function *F = CS.getCalledFunction())
253253 if (F->isExternal())
254254 return NoModRef;
255
255
256256 // Otherwise, if the node is complete, but it is only M or R, return this.
257257 // This can be useful for globals that should be marked const but are not.
258258 if (!N->isModified())
0 //===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the TDDataStructures class, which represents the
134134 delete IndCallMap.begin()->second;
135135 IndCallMap.erase(IndCallMap.begin());
136136 }
137
137
138138
139139 ArgsRemainIncomplete.clear();
140140 GlobalsGraph->removeTriviallyDeadNodes();
169169 DSGraph &G = getOrCreateDSGraph(F);
170170 if (Visited.count(&G)) return;
171171 Visited.insert(&G);
172
172
173173 // Recursively traverse all of the callee graphs.
174174 for (DSGraph::fc_iterator CI = G.fc_begin(), CE = G.fc_end(); CI != CE; ++CI){
175175 Instruction *CallI = CI->getCallSite().getInstruction();
213213 // sites that call into this graph.
214214 std::vector EdgesFromCaller;
215215 std::map >::iterator
216 CEI = CallerEdges.find(&DSG);
216 CEI = CallerEdges.find(&DSG);
217217 if (CEI != CallerEdges.end()) {
218218 std::swap(CEI->second, EdgesFromCaller);
219219 CallerEdges.erase(CEI);
220220 }
221
221
222222 // Sort the caller sites to provide a by-caller-graph ordering.
223223 std::sort(EdgesFromCaller.begin(), EdgesFromCaller.end());
224224
266266 getParent()->getParent()->getName() << "'");
267267 DEBUG(std::cerr << ": " << CF.getFunctionType()->getNumParams()
268268 << " args\n");
269
269
270270 // Get the formal argument and return nodes for the called function and
271271 // merge them with the cloned subgraph.
272272 DSCallSite T1 = DSG.getCallSiteForArguments(CF);
355355 // so we build up a new, private, graph that represents the calls of all
356356 // calls to this set of functions.
357357 std::vector Callees;
358 for (BUDataStructures::ActualCalleesTy::const_iterator I =
358 for (BUDataStructures::ActualCalleesTy::const_iterator I =
359359 BUInfo->callee_begin(CallI), E = BUInfo->callee_end(CallI);
360360 I != E; ++I)
361361 if (!I->second->isExternal())
0 //===- Expressions.cpp - Expression Analysis Utilities --------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines a package of expression analysis utilties:
1010 //
1111 // ClassifyExpression: Analyze an expression to determine the complexity of the
12 // expression, and which other variables it depends on.
12 // expression, and which other variables it depends on.
1313 //
1414 //===----------------------------------------------------------------------===//
1515
2222 using namespace llvm;
2323
2424 ExprType::ExprType(Value *Val) {
25 if (Val)
25 if (Val)
2626 if (ConstantInt *CPI = dyn_cast(Val)) {
2727 Offset = CPI;
2828 Var = 0;
3636 Scale = 0;
3737 }
3838
39 ExprType::ExprType(const ConstantInt *scale, Value *var,
39 ExprType::ExprType(const ConstantInt *scale, Value *var,
4040 const ConstantInt *offset) {
4141 Scale = var ? scale : 0; Var = var; Offset = offset;
4242 ExprTy = Scale ? ScaledLinear : (Var ? Linear : Constant);
6666 inline operator const ConstantInt * () const { return Val; }
6767 inline const ConstantInt *operator->() const { return Val; }
6868 };
69
69
7070 struct DefZero : public DefVal {
7171 inline DefZero(const ConstantInt *val, const Type *ty) : DefVal(val, ty) {}
7272 inline DefZero(const ConstantInt *val) : DefVal(val, val->getType()) {}
7373 };
74
74
7575 struct DefOne : public DefVal {
7676 inline DefOne(const ConstantInt *val, const Type *ty) : DefVal(val, ty) {}
7777 };
159159 // 3. If DefOne is true, a null return value indicates a value of 1, if DefOne
160160 // is false, a null return value indicates a value of 0.
161161 //
162 static inline const ConstantInt *Mul(const ConstantInt *Arg1,
162 static inline const ConstantInt *Mul(const ConstantInt *Arg1,
163163 const ConstantInt *Arg2, bool DefOne) {
164164 assert(Arg1 && Arg2 && "No null arguments should exist now!");
165165 assert(Arg1->getType() == Arg2->getType() && "Types must be compatible!");
167167 // Actually perform the computation now!
168168 Constant *Result = ConstantExpr::get(Instruction::Mul, (Constant*)Arg1,
169169 (Constant*)Arg2);
170 assert(Result && Result->getType() == Arg1->getType() &&
170 assert(Result && Result->getType() == Arg1->getType() &&
171171 "Couldn't perform multiplication!");
172172 ConstantInt *ResultI = cast(Result);
173173
256256 return Expr;
257257 }
258258
259
259
260260 Instruction *I = cast(Expr);
261261 const Type *Ty = I->getType();
262262
276276 return handleAddition(Left, RightNeg, I);
277277 } // end case Instruction::Sub
278278
279 case Instruction::Shl: {
279 case Instruction::Shl: {
280280 ExprType Right(ClassifyExpr(I->getOperand(1)));
281281 if (Right.ExprTy != ExprType::Constant) break;
282282 ExprType Left(ClassifyExpr(I->getOperand(0)));
0 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines a very simple implementation of Andersen's interprocedural
4242 //
4343 // Future Improvements:
4444 // This implementation of Andersen's algorithm is extremely slow. To make it
45 // scale reasonably well, the inclusion constraints could be sorted (easy),
46 // offline variable substitution would be a huge win (straight-forward), and
45 // scale reasonably well, the inclusion constraints could be sorted (easy),
46 // offline variable substitution would be a huge win (straight-forward), and
4747 // online cycle elimination (trickier) might help as well.
4848 //
4949 //===----------------------------------------------------------------------===//
136136 std::map ValueNodes;
137137
138138 /// ObjectNodes - This map contains entries for each memory object in the
139 /// program: globals, alloca's and mallocs.
139 /// program: globals, alloca's and mallocs.
140140 std::map ObjectNodes;
141141
142142 /// ReturnNodes - This map contains an entry for each function in the
160160 Constraint(ConstraintType Ty, Node *D, Node *S)
161161 : Type(Ty), Dest(D), Src(S) {}
162162 };
163
163
164164 /// Constraints - This vector contains a list of all of the constraints
165165 /// identified by the program.
166166 std::vector Constraints;
192192 NullPtr = 1,
193193 NullObject = 2,
194194 };
195
195
196196 public:
197197 bool runOnModule(Module &M) {
198198 InitializeAliasAnalysis(this);
208208 ReturnNodes.clear();
209209 VarargNodes.clear();
210210 EscapingInternalFunctions.clear();
211 std::vector().swap(Constraints);
211 std::vector().swap(Constraints);
212212 return false;
213213 }
214214
231231
232232 //------------------------------------------------
233233 // Implement the AliasAnalysis API
234 //
234 //
235235 AliasResult alias(const Value *V1, unsigned V1Size,
236236 const Value *V2, unsigned V2Size);
237237 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
264264 }
265265 return &GraphNodes[I->second];
266266 }
267
267
268268 /// getObject - Return the node corresponding to the memory object for the
269269 /// specified global or allocation instruction.
270270 Node *getObject(Value *V) {
414414 }
415415 }
416416 }
417
417
418418 AliasAnalysis::getMustAliases(P, RetVals);
419419 }
420420
571571 if (C->getType()->isFirstClassType()) {
572572 if (isa(C->getType()))
573573 N->copyFrom(getNodeForConstantPointer(C));
574
574
575575 } else if (C->isNullValue()) {
576576 N->addPointerTo(&GraphNodes[NullObject]);
577577 return;
606606 F->getName() == "atol" || F->getName() == "atoll" ||
607607 F->getName() == "remove" || F->getName() == "unlink" ||
608608 F->getName() == "rename" || F->getName() == "memcmp" ||
609 F->getName() == "llvm.memset" ||
609 F->getName() == "llvm.memset" ||
610610 F->getName() == "strcmp" || F->getName() == "strncmp" ||
611611 F->getName() == "execl" || F->getName() == "execlp" ||
612612 F->getName() == "execle" || F->getName() == "execv" ||
702702 &GraphNodes[UniversalSet]));
703703 }
704704 }
705
705
706706 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
707707 // Make the function address point to the function object.
708708 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
901901 &GraphNodes[UniversalSet],
902902 getReturnNode(F)));
903903 }
904
904
905905 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
906906 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
907907 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
919919 &GraphNodes[UniversalSet],
920920 getNode(*ArgI)));
921921 }
922
922
923923 // Copy all pointers passed through the varargs section to the varargs node.
924924 if (F->getFunctionType()->isVarArg())
925925 for (; ArgI != ArgE; ++ArgI)
0 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the CallGraph class.
5656 Root = Node; // Found a main, keep track of it!
5757 }
5858 }
59
59
6060 // If this function is not defined in this translation unit, it could call
6161 // anything.
6262 if (F->isExternal() && !F->getIntrinsicID())
112112
113113 // If we didn't find a main function, use the external call graph node
114114 if (Root == 0) Root = ExternalCallingNode;
115
115
116116 return false;
117117 }
118118
147147 OS << F->getName() << "\n";
148148 else
149149 OS << "<>\n";
150
150
151151 for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
152152 I->second->print(OS);
153153 }
0 //===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the CallGraphSCCPass class, which is used for passes
0 //===- FindUnsafePointerTypes.cpp - Check pointer usage safety ------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file defines a pass that can be used to determine, interprocedurally,
9 // This file defines a pass that can be used to determine, interprocedurally,
1010 // which pointer types are accessed unsafely in a program. If there is an
1111 // "unsafe" access to a specific pointer type, transformations that depend on
1212 // type safety cannot be permitted.
1919 //
2020 // Currently, the only allowed operations on pointer types are:
2121 // alloca, malloc, free, getelementptr, load, and store
22 //
22 //
2323 //===----------------------------------------------------------------------===//
2424
2525 #include "llvm/Analysis/FindUnsafePointerTypes.h"
3636 // Provide a command line option to turn on printing of which instructions cause
3737 // a type to become invalid
3838 //
39 static cl::opt
39 static cl::opt
4040 PrintFailures("printunsafeptrinst", cl::Hidden,
4141 cl::desc("Print Unsafe Pointer Access Instructions"));
4242
9595
9696 o << "SafePointerAccess Analysis: Found these unsafe types:\n";
9797 unsigned Counter = 1;
98 for (std::set::const_iterator I = getUnsafeTypes().begin(),
98 for (std::set::const_iterator I = getUnsafeTypes().begin(),
9999 E = getUnsafeTypes().end(); I != E; ++I, ++Counter) {
100
100
101101 o << " #" << Counter << ". ";
102102 CW << **I << "\n";
103103 }
0 //===- FindUsedTypes.cpp - Find all Types used by a module ----------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass is used to seek out all of the types in use by the program. Note
3131 // collection of used types.
3232 //
3333 void FindUsedTypes::IncorporateType(const Type *Ty) {
34 // If ty doesn't already exist in the used types map, add it now, otherwise
34 // If ty doesn't already exist in the used types map, add it now, otherwise
3535 // return.
3636 if (!UsedTypes.insert(Ty).second) return; // Already contain Ty.
37
37
3838 // Make sure to add any types this type references now.
3939 //
4040 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
4444
4545 void FindUsedTypes::IncorporateValue(const Value *V) {
4646 IncorporateType(V->getType());
47
47
4848 // If this is a constant, it could be using other types...
4949 if (const Constant *C = dyn_cast(V)) {
5050 if (!isa(C))
7070 for (Module::iterator MI = m.begin(), ME = m.end(); MI != ME; ++MI) {
7171 IncorporateType(MI->getType());
7272 const Function &F = *MI;
73
73
7474 // Loop over all of the instructions in the function, adding their return
7575 // type as well as the types of their operands.
7676 //
7777 for (const_inst_iterator II = inst_begin(F), IE = inst_end(F);
7878 II != IE; ++II) {
7979 const Instruction &I = *II;
80
80
8181 IncorporateType(I.getType()); // Incorporate the type of the instruction
8282 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
8383 OI != OE; ++OI)
8484 IncorporateValue(*OI); // Insert inst operand types as well
8585 }
8686 }
87
87
8888 return false;
8989 }
9090
0 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This simple pass provides alias and mod/ref information for global values
5757 return I->second;
5858 return 0;
5959 }
60
60
6161 /// FunctionEffect - Capture whether or not this function reads or writes to
6262 /// ANY memory. If not, we can do a lot of aggressive analysis on it.
6363 unsigned FunctionEffect;
9191
9292 //------------------------------------------------
9393 // Implement the AliasAnalysis API
94 //
94 //
9595 AliasResult alias(const Value *V1, unsigned V1Size,
9696 const Value *V2, unsigned V2Size);
9797 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
110110 return DoesNotAccessMemory;
111111 else if ((FR->FunctionEffect & Mod) == 0)
112112 return OnlyReadsMemory;
113 return AliasAnalysis::getModRefBehavior(F, CS, Info);
113 return AliasAnalysis::getModRefBehavior(F, CS, Info);
114114 }
115115
116116 virtual void deleteValue(Value *V);
133133 bool AnalyzeUsesOfGlobal(Value *V, std::vector &Readers,
134134 std::vector &Writers);
135135 };
136
136
137137 RegisterOpt X("globalsmodref-aa",
138138 "Simple mod/ref analysis for globals");
139139 RegisterAnalysisGroup Y;
210210 return true;
211211 } else {
212212 return true;
213 }
213 }
214214 } else if (GlobalValue *GV = dyn_cast(*UI)) {
215215 if (AnalyzeUsesOfGlobal(GV, Readers, Writers)) return true;
216216 } else {
222222 /// AnalyzeCallGraph - At this point, we know the functions where globals are
223223 /// immediately stored to and read from. Propagate this information up the call
224224 /// graph to all callers and compute the mod/ref info for all memory for each
225 /// function.
225 /// function.
226226 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
227227 // We do a bottom-up SCC traversal of the call graph. In other words, we
228228 // visit all callees before callers (leaf-first).
297297 FunctionInfo.erase(SCC[i]->getFunction());
298298 return;
299299 }
300
300
301301 // Otherwise, unless we already know that this function mod/refs memory, scan
302302 // the function bodies to see if there are any explicit loads or stores.
303303 if (FunctionEffect != ModRef) {
304304 for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
305305 for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
306 E = inst_end(SCC[i]->getFunction());
306 E = inst_end(SCC[i]->getFunction());
307307 II != E && FunctionEffect != ModRef; ++II)
308308 if (isa(*II))
309309 FunctionEffect |= Ref;
333333
334334 // If we are at some type of object... return it.
335335 if (const GlobalValue *GV = dyn_cast(V)) return GV;
336
336
337337 // Traverse through different addressing mechanisms...
338338 if (const Instruction *I = dyn_cast(V)) {
339339 if (isa(I) || isa(I))
0 //===- PrintSCC.cpp - Enumerate SCCs in some key graphs -------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file provides passes to print out SCCs in a CFG or a CallGraph.
1616 // analyze -cfgscc to print the SCCs in each CFG of a module.
1717 // analyze -cfgscc -stats to print the #SCCs and the maximum SCC size.
1818 // analyze -cfgscc -debug > /dev/null to watch the algorithm in action.
19 //
19 //
2020 // and similarly:
2121 // analyze -callscc [-stats] [-debug] to print SCCs in the CallGraph
22 //
22 //
2323 // (3) To test the scc_iterator.
2424 //
2525 //===----------------------------------------------------------------------===//
0 //===-- InstCount.cpp - Collects the count of all instructions ------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This pass collects the count of all instructions and reports them
9 // This pass collects the count of all instructions and reports them
1010 //
1111 //===----------------------------------------------------------------------===//
1212
6161 //
6262 bool InstCount::runOnFunction(Function &F) {
6363 unsigned StartMemInsts =
64 NumGetElementPtrInst + NumLoadInst + NumStoreInst + NumCallInst +
64 NumGetElementPtrInst + NumLoadInst + NumStoreInst + NumCallInst +
6565 NumInvokeInst + NumAllocaInst + NumMallocInst + NumFreeInst;
6666 visit(F);
6767 unsigned EndMemInsts =
68 NumGetElementPtrInst + NumLoadInst + NumStoreInst + NumCallInst +
68 NumGetElementPtrInst + NumLoadInst + NumStoreInst + NumCallInst +
6969 NumInvokeInst + NumAllocaInst + NumMallocInst + NumFreeInst;
7070 TotalMemInst += EndMemInsts-StartMemInsts;
7171 return false;
0 //===- Interval.cpp - Interval class code ---------------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file contains the definition of the Interval class, which represents a
3838 void Interval::print(std::ostream &o) const {
3939 o << "-------------------------------------------------------------\n"
4040 << "Interval Contents:\n";
41
41
4242 // Print out all of the basic blocks in the interval...
4343 for (std::vector::const_iterator I = Nodes.begin(),
4444 E = Nodes.end(); I != E; ++I)
0 //===- IntervalPartition.cpp - Interval Partition module code -------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file contains the definition of the IntervalPartition class, which
5454 //
5555 void IntervalPartition::updatePredecessors(Interval *Int) {
5656 BasicBlock *Header = Int->getHeaderNode();
57 for (Interval::succ_iterator I = Int->Successors.begin(),
57 for (Interval::succ_iterator I = Int->Successors.begin(),
5858 E = Int->Successors.end(); I != E; ++I)
5959 getBlockInterval(*I)->Predecessors.push_back(Header);
6060 }
0 //===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements a value numbering pass that value numbers load and call
3838 namespace {
3939 // FIXME: This should not be a FunctionPass.
4040 struct LoadVN : public FunctionPass, public ValueNumbering {
41
41
4242 /// Pass Implementation stuff. This doesn't do any analysis.
4343 ///
4444 bool runOnFunction(Function &) { return false; }
45
45
4646 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
4747 /// and Alias Analysis.
4848 ///
4949 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
50
50
5151 /// getEqualNumberNodes - Return nodes with the same value number as the
5252 /// specified Value. This fills in the argument vector with any equal
5353 /// values.
6262 virtual void deleteValue(Value *V) {
6363 getAnalysis().deleteValue(V);
6464 }
65
65
6666 /// copyValue - This method should be used whenever a preexisting value in
6767 /// the program is copied or cloned, introducing a new value. Note that
6868 /// analysis implementations should tolerate clients that use this method to
108108 // stop searching, returning success.
109109 if (CurBlock == Dom || !Visited.insert(CurBlock).second)
110110 return true;
111
111
112112 // Check whether this block is known transparent or not.
113113 std::map::iterator TBI =
114114 TransparentBlocks.lower_bound(CurBlock);
124124 } else if (!TBI->second)
125125 // This block is known non-transparent, so that path can't be either.
126126 return false;
127
127
128128 // The current block is known to be transparent. The entire path is
129129 // transparent if all of the predecessors paths to the parent is also
130130 // transparent to the memory location.
179179 if (AllOperandsEqual)
180180 IdenticalCalls.push_back(C);
181181 }
182
182
183183 if (IdenticalCalls.empty()) return;
184184
185185 // Eliminate duplicates, which could occur if we chose a value that is passed
211211 Instruction *First = CI, *Second = C;
212212 if (!DomSetInfo.dominates(CI, C))
213213 std::swap(First, Second);
214
214
215215 // Scan the instructions between the calls, checking for stores or
216216 // calls to dangerous functions.
217217 BasicBlock::iterator I = First;
282282 LoadInst *LI = cast(V);
283283 if (LI->isVolatile())
284284 return getAnalysis().getEqualNumberNodes(V, RetVals);
285
285
286286 Value *LoadPtr = LI->getOperand(0);
287287 BasicBlock *LoadBB = LI->getParent();
288288 Function *F = LoadBB->getParent();
350350 // no need to do any global analysis at all.
351351 if (LoadInvalidatedInBBBefore && LoadInvalidatedInBBAfter)
352352 return;
353
353
354354 // Now that we know the value is not neccesarily killed on entry or exit to
355355 // the BB, find out how many load and store instructions (to this location)
356356 // live in each BB in the function.
357357 //
358358 std::map CandidateLoads;
359359 std::set CandidateStores;
360
360
361361 for (Value::use_iterator UI = LoadPtr->use_begin(), UE = LoadPtr->use_end();
362362 UI != UE; ++UI)
363363 if (LoadInst *Cand = dyn_cast(*UI)) {// Is a load of source?
475475
476476 // Stores in the load-bb are handled above.
477477 CandidateStores.erase(LoadBB);
478
478
479479 for (std::set::iterator I = CandidateStores.begin(),
480480 E = CandidateStores.end(); I != E; ++I)
481481 if (DomSetInfo.dominates(*I, LoadBB)) {
0 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines the LoopInfo class that is used to identify natural loops
174174 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
175175 assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
176176 SLP->SubLoops.erase(I); // Remove from parent...
177
177
178178 // Add the subloop to THIS loop...
179179 SubLoop->ParentLoop = L;
180180 L->SubLoops.push_back(SubLoop);
182182
183183 // Normal case, add the block to our loop...
184184 L->Blocks.push_back(X);
185
185
186186 // Add all of the predecessors of X to the end of the work stack...
187187 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
188188 }
242242 --i; // We just shrunk the SubLoops list.
243243 }
244244 }
245 }
245 }
246246 }
247247 }
248248
262262 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
263263 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
264264 NewChild->ParentLoop = 0;
265
266 InsertLoopInto(NewChild, NewParent);
265
266 InsertLoopInto(NewChild, NewParent);
267267 }
268268
269269 /// InsertLoopInto - This inserts loop L into the specified parent loop. If the
272272 void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
273273 BasicBlock *LHeader = L->getHeader();
274274 assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
275
275
276276 // Check to see if it belongs in a child loop...
277277 for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
278278 if (Parent->SubLoops[i]->contains(LHeader)) {
279279 InsertLoopInto(L, Parent->SubLoops[i]);
280280 return;
281 }
281 }
282282
283283 // If not, insert it here!
284284 Parent->SubLoops.push_back(L);
324324 if (I != BBMap.end()) {
325325 for (Loop *L = I->second; L; L = L->getParentLoop())
326326 L->removeBlockFromLoop(BB);
327
327
328328 BBMap.erase(I);
329329 }
330330 }
366366 return 0; // Multiple predecessors outside the loop
367367 Out = *PI;
368368 }
369
369
370370 // Make sure there is only one exit out of the preheader...
371371 succ_iterator SI = succ_begin(Out);
372372 ++SI;
438438 Instruction *Inc = getCanonicalInductionVariableIncrement();
439439 if (Inc == 0) return 0;
440440 PHINode *IV = cast(Inc->getOperand(0));
441
441
442442 BasicBlock *BackedgeBlock =
443443 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
444444
452452 } else if (SCI->getOpcode() == Instruction::SetEQ) {
453453 return SCI->getOperand(1);
454454 }
455
455
456456 return 0;
457457 }
458458
0 //===- PostDominators.cpp - Post-Dominator Calculation --------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the post-dominator construction algorithms.
7272 //
7373 while (Doms[*SI].size() == 0) ++SI;
7474 WorkingSet = Doms[*SI];
75
75
7676 for (++SI; SI != SE; ++SI) { // Intersect all of the successor sets
7777 DomSetType &SuccSet = Doms[*SI];
7878 if (SuccSet.size())
114114 // Loop over all of the nodes that have dominators... figuring out the IDOM
115115 // for each node...
116116 //
117 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
117 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
118118 DI != DEnd; ++DI) {
119119 BasicBlock *BB = DI->first;
120120 const DominatorSet::DomSetType &Dominators = DI->second;
132132 for (; I != End; ++I) { // Iterate over dominators...
133133 // All of our dominators should form a chain, where the number of elements
134134 // in the dominator set indicates what level the node is at in the chain.
135 // We want the node immediately above us, so it will have an identical
135 // We want the node immediately above us, so it will have an identical
136136 // dominator set, except that BB will not dominate it... therefore it's
137137 // dominator set size will be one less than BB's...
138138 //
190190 // dominator set size will be one less than BB's...
191191 //
192192 if (DS.getDominators(*I).size() == DomSetSize - 1) {
193 // We know that the immediate dominator should already have a node,
193 // We know that the immediate dominator should already have a node,
194194 // because we are traversing the CFG in depth first order!
195195 //
196196 Node *IDomNode = Nodes[*I];
197197 assert(IDomNode && "No node for IDOM?");
198
198
199199 // Add a new tree node for this BasicBlock, and link it as a child of
200200 // IDomNode
201201 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
213213 H("postdomfrontier", "Post-Dominance Frontier Construction", true);
214214
215215 const DominanceFrontier::DomSetType &
216 PostDominanceFrontier::calculate(const PostDominatorTree &DT,
216 PostDominanceFrontier::calculate(const PostDominatorTree &DT,
217217 const DominatorTree::Node *Node) {
218218 // Loop over CFG successors to calculate DFlocal[Node]
219219 BasicBlock *BB = Node->getBlock();
0 //===- ProfileInfo.cpp - Profile Info Interface ---------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the abstract ProfileInfo interface, and the default
8282
8383 namespace {
8484 struct NoProfileInfo : public ImmutablePass, public ProfileInfo {};
85
85
8686 // Register this pass...
8787 RegisterOpt
8888 X("no-profile", "No Profile Information");
0 //===- ProfileInfoLoad.cpp - Load profile information from disk -----------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // The ProfileInfoLoader class is used to load and represent profiling
2525 //
2626 static inline unsigned ByteSwap(unsigned Var, bool Really) {
2727 if (!Really) return Var;
28 return ((Var & (255<< 0)) << 24) |
29 ((Var & (255<< 8)) << 8) |
30 ((Var & (255<<16)) >> 8) |
28 return ((Var & (255<< 0)) << 24) |
29 ((Var & (255<< 8)) << 8) |
30 ((Var & (255<<16)) >> 8) |
3131 ((Var & (255<<24)) >> 24);
3232 }
3333
5656 // Make sure we have enough space...
5757 if (Data.size() < NumEntries)
5858 Data.resize(NumEntries);
59
59
6060 // Accumulate the data we just read into the data.
6161 if (!ShouldByteSwap) {
6262 for (unsigned i = 0; i != NumEntries; ++i)
111111 CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength]));
112112 break;
113113 }
114
114
115115 case FunctionInfo:
116116 ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts);
117117 break;
118
118
119119 case BlockInfo:
120120 ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts);
121121 break;
133133 exit(1);
134134 }
135135 }
136
136
137137 fclose(F);
138138 }
139139
150150 // their entry blocks were executed.
151151 std::vector > BlockCounts;
152152 getBlockCounts(BlockCounts);
153
153
154154 for (unsigned i = 0, e = BlockCounts.size(); i != e; ++i)
155155 if (&BlockCounts[i].first->getParent()->front() == BlockCounts[i].first)
156156 Counts.push_back(std::make_pair(BlockCounts[i].first->getParent(),
160160 }
161161 return;
162162 }
163
163
164164 unsigned Counter = 0;
165165 for (Module::iterator I = M.begin(), E = M.end();
166166 I != E && Counter != FunctionCounts.size(); ++I)
0 //===- ProfileInfoLoaderPass.cpp - LLVM Pass to load profile info ---------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements a concrete implementation of profiling information that
4747 /// run - Load the profile information from the specified file.
4848 virtual bool runOnModule(Module &M);
4949 };
50
50
5151 RegisterPass
5252 X("profile-loader", "Load profile information from llvmprof.out",
5353 PassInfo::Analysis|PassInfo::Optimization);
6868 ProfileInfoLoader PIL("profile-loader", Filename, M);
6969 EdgeCounts.clear();
7070 bool PrintedWarning = false;
71
71
7272 std::vector > ECs;
7373 PIL.getEdgeCounts(ECs);
7474 for (unsigned i = 0, e = ECs.size(); i != e; ++i) {
0 //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file contains the implementation of the scalar evolution analysis
2727 // have folders that are used to build the *canonical* representation for a
2828 // particular expression. These folders are capable of using a variety of
2929 // rewrite rules to simplify the expressions.
30 //
30 //
3131 // Once the folders are defined, we can implement the more interesting
3232 // higher-level code, such as the code that recognizes PHI nodes of various
3333 // types, computes the execution count of a loop, etc.
162162 // particular value. Don't use a SCEVHandle here, or else the object will
163163 // never be deleted!
164164 static std::map SCEVConstants;
165
165
166166
167167 SCEVConstant::~SCEVConstant() {
168168 SCEVConstants.erase(V);
174174 const Type *NewTy = V->getType()->getUnsignedVersion();
175175 V = cast(ConstantExpr::getCast(V, NewTy));
176176 }
177
177
178178 SCEVConstant *&R = SCEVConstants[V];
179179 if (R == 0) R = new SCEVConstant(V);
180180 return R;
336336 for (++i; i != e; ++i)
337337 NewOps.push_back(getOperand(i)->
338338 replaceSymbolicValuesWithConcrete(Sym, Conc));
339
339
340340 return get(NewOps, L);
341341 }
342342 }
450450 /// specified signed integer value and return a SCEV for the constant.
451451 SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
452452 Constant *C;
453 if (Val == 0)
453 if (Val == 0)
454454 C = Constant::getNullValue(Ty);
455455 else if (Ty->isFloatingPoint())
456456 C = ConstantFP::get(Ty, Val);
482482 SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
483483 if (SCEVConstant *VC = dyn_cast(V))
484484 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
485
485
486486 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
487487 }
488488
510510 const Type *Ty = V->getType();
511511 if (NumSteps == 0)
512512 return SCEVUnknown::getIntegerSCEV(1, Ty);
513
513
514514 SCEVHandle Result = V;
515515 for (unsigned i = 1; i != NumSteps; ++i)
516516 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
622622 }
623623
624624 if (Ops.size() == 1) return Ops[0];
625
625
626626 // Okay, check to see if the same value occurs in the operand list twice. If
627627 // so, merge them together into an multiply expression. Since we sorted the
628628 // list, these values are required to be adjacent.
695695 Ops.push_back(OuterMul);
696696 return SCEVAddExpr::get(Ops);
697697 }
698
698
699699 // Check this multiply against other multiplies being added together.
700700 for (unsigned OtherMulIdx = Idx+1;
701701 OtherMulIdx < Ops.size() && isa(Ops[OtherMulIdx]);
867867
868868 if (Ops.size() == 1)
869869 return Ops[0];
870
870
871871 // If there are mul operands inline them all into this expression.
872872 if (Idx < Ops.size()) {
873873 bool DeletedMul = false;
10851085 /// properties. An instruction maps to null if we are unable to compute its
10861086 /// exit value.
10871087 std::map ConstantEvolutionLoopExitValue;
1088
1088
10891089 public:
10901090 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
10911091 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
12291229 // from outside the loop, and one from inside.
12301230 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
12311231 unsigned BackEdge = IncomingEdge^1;
1232
1232
12331233 // While we are analyzing this PHI node, handle its value symbolically.
12341234 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
12351235 assert(Scalars.find(PN) == Scalars.end() &&
12851285
12861286 return SymbolicName;
12871287 }
1288
1288
12891289 // If it's not a loop phi, we can't handle it yet.
12901290 return SCEVUnknown::get(PN);
12911291 }
12951295 SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
12961296 const Type *SrcTy = CI->getOperand(0)->getType();
12971297 const Type *DestTy = CI->getType();
1298
1298
12991299 // If this is a noop cast (ie, conversion from int to uint), ignore it.
13001300 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
13011301 return getSCEV(CI->getOperand(0));
1302
1302
13031303 if (SrcTy->isInteger() && DestTy->isInteger()) {
13041304 // Otherwise, if this is a truncating integer cast, we can represent this
13051305 // cast.
14851485 if (CompVal) {
14861486 // Form the constant range.
14871487 ConstantRange CompRange(Cond, CompVal);
1488
1488
14891489 // Now that we have it, if it's signed, convert it to an unsigned
14901490 // range.
14911491 if (CompRange.getLower()->getType()->isSigned()) {
14941494 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
14951495 CompRange = ConstantRange(NewL, NewU);
14961496 }
1497
1497
14981498 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
14991499 if (!isa(Ret)) return Ret;
15001500 }
15011501 }
1502
1502
15031503 switch (Cond) {
15041504 case Instruction::SetNE: // while (X != Y)
15051505 // Convert to: while (X-Y != 0)
15441544 /// the addressed element of the initializer or null if the index expression is
15451545 /// invalid.
15461546 static Constant *
1547 GetAddressedElementFromGlobal(GlobalVariable *GV,
1547 GetAddressedElementFromGlobal(GlobalVariable *GV,
15481548 const std::vector &Indices) {
15491549 Constant *Init = GV->getInitializer();
15501550 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
15761576 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
15771577 /// 'setcc load X, cst', try to se if we can compute the trip count.
15781578 SCEVHandle ScalarEvolutionsImpl::
1579 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1579 ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
15801580 const Loop *L, unsigned SetCCOpcode) {
15811581 if (LI->isVolatile()) return UnknownValue;
15821582
16551655 if (isa(I) || isa(I) ||
16561656 isa(I) || isa(I) || isa(I))
16571657 return true;
1658
1658
16591659 if (const CallInst *CI = dyn_cast(I))
16601660 if (const Function *F = CI->getCalledFunction())
16611661 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
17121712 // If we won't be able to constant fold this expression even if the operands
17131713 // are constants, return early.
17141714 if (!CanConstantFold(I)) return 0;
1715
1715
17161716 // Otherwise, we can evaluate this instruction if all of its operands are
17171717 // constant or derived from a PHI node themselves.
17181718 PHINode *PHI = 0;
17641764 if (I != ConstantEvolutionLoopExitValue.end())
17651765 return I->second;
17661766
1767 if (Its > MaxBruteForceIterations)
1767 if (Its > MaxBruteForceIterations)
17681768 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
17691769
17701770 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
18411841 ++NumBruteForceTripCountsComputed;
18421842 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
18431843 }
1844
1844
18451845 // Compute the value of the PHI node for the next iteration.
18461846 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
18471847 if (NextPHI == 0 || NextPHI == PHIVal)
18601860 // FIXME: this should be turned into a virtual method on SCEV!
18611861
18621862 if (isa(V)) return V;
1863
1863
18641864 // If this instruction is evolves from a constant-evolving PHI, compute the
18651865 // exit value from the loop without using SCEVs.
18661866 if (SCEVUnknown *SU = dyn_cast(V)) {
19651965 if (IterationCount == UnknownValue) return UnknownValue;
19661966 IterationCount = getTruncateOrZeroExtend(IterationCount,
19671967 AddRec->getType());
1968
1968
19691969 // If the value is affine, simplify the expression evaluation to just
19701970 // Start + Step*IterationCount.
19711971 if (AddRec->isAffine())
19941994 SCEVConstant *L = dyn_cast(AddRec->getOperand(0));
19951995 SCEVConstant *M = dyn_cast(AddRec->getOperand(1));
19961996 SCEVConstant *N = dyn_cast(AddRec->getOperand(2));
1997
1997
19981998 // We currently can only solve this if the coefficients are constants.
19991999 if (!L || !M || !N) {
20002000 SCEV *CNC = new SCEVCouldNotCompute();
20022002 }
20032003
20042004 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
2005
2005
20062006 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
20072007 Constant *C = L->getValue();
20082008 // The B coefficient is M-N/2
20112011 Two));
20122012 // The A coefficient is N/2
20132013 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
2014
2014
20152015 // Compute the B^2-4ac term.
20162016 Constant *SqrtTerm =
20172017 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
20342034
20352035 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
20362036 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
2037
2037
20382038 Constant *NegB = ConstantExpr::getNeg(B);
20392039 Constant *TwoA = ConstantExpr::getMul(A, Two);
2040
2040
20412041 // The divisions must be performed as signed divisions.
20422042 const Type *SignedTy = NegB->getType()->getSignedVersion();
20432043 NegB = ConstantExpr::getCast(NegB, SignedTy);
20442044 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
20452045 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
2046
2046
20472047 Constant *Solution1 =
20482048 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
20492049 Constant *Solution2 =
21162116 R2->getValue()))) {
21172117 if (CB != ConstantBool::True)
21182118 std::swap(R1, R2); // R1 is the minimum root now.
2119
2119
21202120 // We can only use this value if the chrec ends up with an exact zero
21212121 // value at this index. When solving for "X*X != 5", for example, we
21222122 // should not accept a root of 2.
21272127 }
21282128 }
21292129 }
2130
2130
21312131 return UnknownValue;
21322132 }
21332133
21382138 // Loops that look like: while (X == 0) are very strange indeed. We don't
21392139 // handle them yet except for the trivial case. This could be expanded in the
21402140 // future as needed.
2141
2141
21422142 // If the value is a constant, check to se