llvm.org GIT mirror llvm / 3da94ae
Remove trailing whitespace git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@21428 91177308-0d34-0410-b5e6-96231b3b80d8 Misha Brukman 14 years ago
65 changed file(s) with 570 addition(s) and 570 deletion(s). Raw diff Collapse all Expand all
0 //===- AnalysisWrappers.cpp - Wrappers around non-pass analyses -----------===//
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 pass wrappers around LLVM analyses that don't make sense to
5555 }
5656
5757 void print(std::ostream &OS) const {}
58
58
5959 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
6060 AU.setPreservesAll();
6161 }
0 //===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
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 several printers for various different types of graphs used
2626 std::string Filename = GraphName + ".dot";
2727 O << "Writing '" << Filename << "'...";
2828 std::ofstream F(Filename.c_str());
29
29
3030 if (F.good())
3131 WriteGraph(F, GT);
3232 else
4545 static std::string getGraphName(CallGraph *F) {
4646 return "Call Graph";
4747 }
48
48
4949 static std::string getNodeLabel(CallGraphNode *Node, CallGraph *Graph) {
5050 if (Node->getFunction())
5151 return ((Value*)Node->getFunction())->getName();
6464 }
6565
6666 void print(std::ostream &OS) const {}
67
67
6868 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
6969 AU.addRequired();
7070 AU.setPreservesAll();
0 //===- analyze.cpp - The LLVM analyze utility -----------------------------===//
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 utility is designed to print out the results of running various analysis
10 // passes on a program. This is useful for understanding a program, or for
10 // passes on a program. This is useful for understanding a program, or for
1111 // debugging an analysis pass.
1212 //
1313 // analyze --help - Output information about command line switches
3636 virtual bool runOnModule(Module &M) {
3737 std::cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
3838 getAnalysisID(PassToPrint).print(std::cout, &M);
39
39
4040 // Get and print pass...
4141 return false;
4242 }
43
43
4444 virtual const char *getPassName() const { return "'Pass' Printer"; }
4545
4646 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149149 // Create a new optimization pass for each one specified on the command line
150150 for (unsigned i = 0; i < AnalysesList.size(); ++i) {
151151 const PassInfo *Analysis = AnalysesList[i];
152
152
153153 if (Analysis->getNormalCtor()) {
154154 Pass *P = Analysis->getNormalCtor()();
155155 Passes.add(P);
0 //===- BugDriver.cpp - Top-Level BugPoint class 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 class contains all of the shared state and information that is used by
3434 // otherwise the raw input run through an interpreter is used as the reference
3535 // source.
3636 //
37 cl::opt
37 cl::opt
3838 OutputFile("output", cl::desc("Specify a reference program output "
3939 "(for miscompilation detection)"));
4040 }
0 //===- BugDriver.h - Top-Level BugPoint class -------------------*- 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 class contains all of the shared state and information that is used by
7575 /// reasonable, and figure out exactly which pass is crashing.
7676 ///
7777 bool debugOptimizerCrash();
78
78
7979 /// debugCodeGeneratorCrash - This method is called when the code generator
8080 /// crashes on an input. It attempts to reduce the input as much as possible
8181 /// while still causing the code generator to crash.
138138 void switchToInterpreter(AbstractInterpreter *AI) {
139139 Interpreter = AI;
140140 }
141
141
142142 /// setNewProgram - If we reduce or update the program somehow, call this
143143 /// method to update bugdriver with it. This deletes the old module and sets
144144 /// the specified one as the current program.
0 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
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 bugpoint internals that narrow down compilation crashes
3535 BugDriver &BD;
3636 public:
3737 ReducePassList(BugDriver &bd) : BD(bd) {}
38
38
3939 // doTest - Return true iff running the "removed" passes succeeds, and
4040 // running the "Kept" passes fail when run on the output of the "removed"
4141 // passes. If we return true, we update the current module of bugpoint.
7171
7272 std::cout << "Checking to see if these passes crash: "
7373 << getPassesString(Suffix) << ": ";
74
74
7575 if (BD.runPasses(Suffix)) {
7676 delete OrigProgram; // The suffix crashes alone...
7777 return KeepSuffix;
9393 ReduceCrashingFunctions(BugDriver &bd,
9494 bool (*testFn)(BugDriver &, Module *))
9595 : BD(bd), TestFn(testFn) {}
96
96
9797 virtual TestResult doTest(std::vector &Prefix,
9898 std::vector &Kept) {
9999 if (!Kept.empty() && TestFuncs(Kept))
102102 return KeepPrefix;
103103 return NoFailure;
104104 }
105
105
106106 bool TestFuncs(std::vector &Prefix);
107107 };
108108 }
110110 bool ReduceCrashingFunctions::TestFuncs(std::vector &Funcs) {
111111 // Clone the program to try hacking it apart...
112112 Module *M = CloneModule(BD.getProgram());
113
113
114114 // Convert list to set for fast lookup...
115115 std::set Functions;
116116 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
117 Function *CMF = M->getFunction(Funcs[i]->getName(),
117 Function *CMF = M->getFunction(Funcs[i]->getName(),
118118 Funcs[i]->getFunctionType());
119119 assert(CMF && "Function not in module?!");
120120 Functions.insert(CMF);
156156 public:
157157 ReduceCrashingBlocks(BugDriver &bd, bool (*testFn)(BugDriver &, Module *))
158158 : BD(bd), TestFn(testFn) {}
159
159
160160 virtual TestResult doTest(std::vector &Prefix,
161161 std::vector &Kept) {
162162 if (!Kept.empty() && TestBlocks(Kept))
165165 return KeepPrefix;
166166 return NoFailure;
167167 }
168
168
169169 bool TestBlocks(std::vector &Prefix);
170170 };
171171 }
173173 bool ReduceCrashingBlocks::TestBlocks(std::vector &BBs) {
174174 // Clone the program to try hacking it apart...
175175 Module *M = CloneModule(BD.getProgram());
176
176
177177 // Convert list to set for fast lookup...
178178 std::set Blocks;
179179 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
213213
214214 // Delete the old terminator instruction...
215215 BB->getInstList().pop_back();
216
216
217217 // Add a new return instruction of the appropriate type...
218218 const Type *RetTy = BB->getParent()->getReturnType();
219219 new ReturnInst(RetTy == Type::VoidTy ? 0 :
273273 I->setLinkage(GlobalValue::ExternalLinkage);
274274 DeletedInit = true;
275275 }
276
276
277277 if (!DeletedInit) {
278278 delete M; // No change made...
279279 } else {
289289 }
290290 }
291291 }
292
292
293293 // Now try to reduce the number of functions in the module to something small.
294294 std::vector Functions;
295295 for (Module::iterator I = BD.getProgram()->begin(),
342342 //
343343 unsigned InstructionsToSkipBeforeDeleting = 0;
344344 TryAgain:
345
345
346346 // Loop over all of the (non-terminator) instructions remaining in the
347347 // function, attempting to delete them.
348348 unsigned CurInstructionNum = 0;
358358 } else {
359359 std::cout << "Checking instruction '" << I->getName() << "': ";
360360 Module *M = BD.deleteInstructionFromProgram(I, Simplification);
361
361
362362 // Find out if the pass still crashes on this pass...
363363 if (TestFn(BD, M)) {
364364 // Yup, it does, we delete the old module, and continue trying
368368 InstructionsToSkipBeforeDeleting = CurInstructionNum;
369369 goto TryAgain; // I wish I had a multi-level break here!
370370 }
371
371
372372 // This pass didn't crash without this instruction, try the next
373373 // one.
374374 delete M;
378378 InstructionsToSkipBeforeDeleting = 0;
379379 goto TryAgain;
380380 }
381
381
382382 } while (Simplification);
383383
384384 // Try to clean up the testcase by running funcresolve and globaldce...
385385 std::cout << "\n*** Attempting to perform final cleanups: ";
386386 Module *M = CloneModule(BD.getProgram());
387387 M = BD.performFinalCleanups(M, true);
388
388
389389 // Find out if the pass still crashes on the cleaned up program...
390390 if (TestFn(BD, M)) {
391391 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
397397 if (AnyReduction)
398398 BD.EmitProgressBytecode("reduced-simplified");
399399
400 return false;
400 return false;
401401 }
402402
403403 static bool TestForOptimizerCrash(BugDriver &BD, Module *M) {
0 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
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 code used to execute the program utilizing one of the
275275 #endif
276276
277277 std::string SharedObjectFile;
278 if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
278 if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
279279 SharedObjectFile))
280280 exit(1);
281281
302302 // If we're checking the program exit code, assume anything nonzero is bad.
303303 if (CheckProgramExitCode && ProgramExitedNonzero) {
304304 Output.destroyFile();
305 if (RemoveBytecode)
305 if (RemoveBytecode)
306306 sys::Path(BytecodeFile).destroyFile();
307307 return true;
308308 }
318318 }
319319 FilesDifferent = true;
320320 }
321
321
322322 // Remove the generated output.
323323 Output.destroyFile();
324324
0 //===- ExtractFunction.cpp - Extract a function from Program --------------===//
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 several methods that are used to extract functions,
103103 // Make all functions external, so GlobalDCE doesn't delete them...
104104 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
105105 I->setLinkage(GlobalValue::ExternalLinkage);
106
106
107107 std::vector CleanupPasses;
108108 CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
109109 CleanupPasses.push_back(getPI(createGlobalDCEPass()));
154154 for (unsigned i = 0, e = M->size(); i != e; ++i)
155155 ++MI;
156156 }
157
157
158158 return NewM;
159159 }
160160
250250
251251 for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
252252 ExtractBasicBlock(BlocksToExtract[i]);
253
253
254254 return !BlocksToExtract.empty();
255255 }
256256
0 //===- ListReducer.h - Trim down list while retaining property --*- 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 class is to be used as a base class for operations that want to zero in
4747 case KeepPrefix:
4848 if (TheList.size() == 1) // we are done, it's the base case and it fails
4949 return true;
50 else
50 else
5151 break; // there's definitely an error, but we need to narrow it down
5252
5353 case KeepSuffix:
106106 Changed = true;
107107 }
108108 }
109 // This can take a long time if left uncontrolled. For now, don't
109 // This can take a long time if left uncontrolled. For now, don't
110110 // iterate.
111111 break;
112112 }
0 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
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 optimizer and code generation miscompilation debugging
3636 BugDriver &BD;
3737 public:
3838 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
39
39
4040 virtual TestResult doTest(std::vector &Prefix,
4141 std::vector &Suffix);
4242 };
5555
5656 std::string BytecodeResult;
5757 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
58 std::cerr << " Error running this sequence of passes"
58 std::cerr << " Error running this sequence of passes"
5959 << " on the input program!\n";
6060 BD.setPassesToRun(Suffix);
6161 BD.EmitProgressBytecode("pass-error", false);
8888 // prefix passes, then discard the prefix passes.
8989 //
9090 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
91 std::cerr << " Error running this sequence of passes"
91 std::cerr << " Error running this sequence of passes"
9292 << " on the input program!\n";
9393 BD.setPassesToRun(Prefix);
9494 BD.EmitProgressBytecode("pass-error", false);
117117 // Don't check if there are no passes in the suffix.
118118 if (Suffix.empty())
119119 return NoFailure;
120
120
121121 std::cout << "Checking to see if '" << getPassesString(Suffix)
122122 << "' passes compile correctly after the '"
123123 << getPassesString(Prefix) << "' passes: ";
124124
125125 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
126126 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
127 std::cerr << " Error running this sequence of passes"
127 std::cerr << " Error running this sequence of passes"
128128 << " on the input program!\n";
129129 BD.setPassesToRun(Suffix);
130130 BD.EmitProgressBytecode("pass-error", false);
152152 ReduceMiscompilingFunctions(BugDriver &bd,
153153 bool (*F)(BugDriver &, Module *, Module *))
154154 : BD(bd), TestFn(F) {}
155
155
156156 virtual TestResult doTest(std::vector &Prefix,
157157 std::vector &Suffix) {
158158 if (!Suffix.empty() && TestFuncs(Suffix))
161161 return KeepPrefix;
162162 return NoFailure;
163163 }
164
164
165165 bool TestFuncs(const std::vector &Prefix);
166166 };
167167 }
279279 return MadeChange;
280280 }
281281 BD.switchToInterpreter(AI);
282
282
283283 std::cout << " Testing after loop extraction:\n";
284284 // Clone modules, the tester function will free them.
285285 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
342342 bool (*F)(BugDriver &, Module *, Module *),
343343 const std::vector &Fns)
344344 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
345
345
346346 virtual TestResult doTest(std::vector &Prefix,
347347 std::vector &Suffix) {
348348 if (!Suffix.empty() && TestFuncs(Suffix))
351351 return KeepPrefix;
352352 return NoFailure;
353353 }
354
354
355355 bool TestFuncs(const std::vector &Prefix);
356356 };
357357 }
505505
506506 // Do the reduction...
507507 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
508
508
509509 std::cout << "\n*** The following function"
510510 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
511511 << " being miscompiled: ";
524524
525525 // Do the reduction...
526526 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
527
527
528528 std::cout << "\n*** The following function"
529529 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
530530 << " being miscompiled: ";
585585 ToNotOptimize = swapProgramIn(ToNotOptimize);
586586 EmitProgressBytecode("tonotoptimize", true);
587587 setNewProgram(ToNotOptimize); // Delete hacked module.
588
588
589589 std::cout << " Portion that is input to optimizer: ";
590590 ToOptimize = swapProgramIn(ToOptimize);
591591 EmitProgressBytecode("tooptimize");
613613 // Rename it
614614 oldMain->setName("llvm_bugpoint_old_main");
615615 // Create a NEW `main' function with same type in the test module.
616 Function *newMain = new Function(oldMain->getFunctionType(),
616 Function *newMain = new Function(oldMain->getFunctionType(),
617617 GlobalValue::ExternalLinkage,
618618 "main", Test);
619619 // Create an `oldmain' prototype in the test module, which will
620620 // corresponds to the real main function in the same module.
621 Function *oldMainProto = new Function(oldMain->getFunctionType(),
621 Function *oldMainProto = new Function(oldMain->getFunctionType(),
622622 GlobalValue::ExternalLinkage,
623623 oldMain->getName(), Test);
624624 // Set up and remember the argument list for the main function.
633633 // Call the old main function and return its result
634634 BasicBlock *BB = new BasicBlock("entry", newMain);
635635 CallInst *call = new CallInst(oldMainProto, args, "", BB);
636
636
637637 // If the type of old function wasn't void, return value of call
638638 new ReturnInst(call, BB);
639639 }
642642 // module cannot directly reference any functions defined in the test
643643 // module. Instead, we use a JIT API call to dynamically resolve the
644644 // symbol.
645
645
646646 // Add the resolver to the Safe module.
647647 // Prototype: void *getPointerToNamedFunction(const char* Name)
648 Function *resolverFunc =
648 Function *resolverFunc =
649649 Safe->getOrInsertFunction("getPointerToNamedFunction",
650650 PointerType::get(Type::SByteTy),
651651 PointerType::get(Type::SByteTy), 0);
652
652
653653 // Use the function we just added to get addresses of functions we need.
654654 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
655655 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
662662 Constant *InitArray = ConstantArray::get(F->getName());
663663 GlobalVariable *funcName =
664664 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
665 GlobalValue::InternalLinkage, InitArray,
665 GlobalValue::InternalLinkage, InitArray,
666666 F->getName() + "_name", Safe);
667667
668668 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
689689 // Resolve the call to function F via the JIT API:
690690 //
691691 // call resolver(GetElementPtr...)
692 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
692 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
693693 "resolver");
694694 Header->getInstList().push_back(resolve);
695695 // cast the result from the resolver to correctly-typed function
0 //===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
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 an interface that allows bugpoint to run various passes
194194 std::string BytecodeResult;
195195 if (runPasses(Passes, BytecodeResult, false/*delete*/, true/*quiet*/)) {
196196 if (AutoDebugCrashes) {
197 std::cerr << " Error running this sequence of passes"
197 std::cerr << " Error running this sequence of passes"
198198 << " on the input program!\n";
199199 delete OldProgram;
200200 EmitProgressBytecode("pass-error", false);
0 //===- TestPasses.cpp - "buggy" passes used to test bugpoint --------------===//
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 "buggy" passes that are used to test bugpoint, to check
0 //===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
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 program is an automated compiler debugger tool. It is used to narrow
0 //===- extract.cpp - LLVM function extraction utility ---------------------===//
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 utility changes the input module to only contain a single function,
2727 static cl::opt
2828 InputFilename(cl::Positional, cl::desc(""),
2929 cl::init("-"), cl::value_desc("filename"));
30
30
3131 static cl::opt
32 OutputFilename("o", cl::desc("Specify output filename"),
32 OutputFilename("o", cl::desc("Specify output filename"),
3333 cl::value_desc("filename"), cl::init("-"));
3434
3535 static cl::opt
8787 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
8888 } else { // Specified stdout
8989 // FIXME: cout is not binary!
90 Out = &std::cout;
90 Out = &std::cout;
9191 }
9292
9393 Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
0 //===-- gccas.cpp - The "optimizing assembler" used by the GCC frontend ---===//
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 utility is designed to be used by the GCC frontend for creating bytecode
3232 cl::opt
3333 InputFilename(cl::Positional,cl::desc(""),cl::init("-"));
3434
35 cl::opt
35 cl::opt
3636 OutputFilename("o", cl::desc("Override output filename"),
3737 cl::value_desc("filename"));
3838
39 cl::opt
39 cl::opt
4040 Verify("verify", cl::desc("Verify each pass result"));
4141
4242 cl::opt
5050 StripDebug("strip-debug",
5151 cl::desc("Strip debugger symbol info from translation unit"));
5252
53 cl::opt
53 cl::opt
5454 NoCompress("disable-compression", cl::init(false),
5555 cl::desc("Don't compress the generated bytecode"));
5656
6262 static inline void addPass(PassManager &PM, Pass *P) {
6363 // Add the pass to the pass manager...
6464 PM.add(P);
65
65
6666 // If we are verifying all of the intermediate steps, add the verifier...
6767 if (Verify) PM.add(createVerifierPass());
6868 }
127127
128128 int main(int argc, char **argv) {
129129 try {
130 cl::ParseCommandLineOptions(argc, argv,
130 cl::ParseCommandLineOptions(argc, argv,
131131 " llvm .s -> .o assembler for GCC\n");
132132 sys::PrintStackTraceOnErrorSignal();
133133
174174 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
175175 }
176176
177
177
178178 if (!Out->good()) {
179179 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
180180 return 1;
0 //===- GenerateCode.cpp - Functions for generating executable files ------===//
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 functions for generating executable files once linking
153153
154154 // Make sure the -L path has a '/' character
155155 // because llvm-g++ passes them without the ending
156 // '/' char and sys::Path doesn't think it is a
157 // directory (see: sys::Path::isDirectory) without it
156 // '/' char and sys::Path doesn't think it is a
157 // directory (see: sys::Path::isDirectory) without it
158158 std::string dir = LibPath;
159159 if ( dir[dir.length()-1] != '/' )
160160 dir.append("/");
405405 //
406406 // Note:
407407 // When gccld is called from the llvm-gxx frontends, the -L paths for
408 // the LLVM cfrontend install paths are appended. We don't want the
408 // the LLVM cfrontend install paths are appended. We don't want the
409409 // native linker to use these -L paths as they contain bytecode files.
410410 // Further, we don't want any -L paths that contain bytecode shared
411411 // libraries or true bytecode archive files. We omit them in all such
416416 args.push_back(LibPaths[index].c_str());
417417 }
418418 }
419
419
420420 // Add in the libraries to link.
421421 for (unsigned index = 0; index < Libraries.size(); index++) {
422422 if (Libraries[index] != "crtend") {
0 //===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
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 utility is intended to be compatible with GCC, and follows standard
3737 using namespace llvm;
3838
3939 namespace {
40 cl::list
40 cl::list
4141 InputFilenames(cl::Positional, cl::desc(""),
4242 cl::OneOrMore);
4343
44 cl::opt
44 cl::opt
4545 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
4646 cl::value_desc("filename"));
4747
4848 cl::opt
4949 Verbose("v", cl::desc("Print information about actions taken"));
5050
51 cl::list
51 cl::list
5252 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
5353 cl::value_desc("directory"));
5454
55 cl::list
55 cl::list
5656 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
5757 cl::value_desc("library prefix"));
5858
9090 cl::opt
9191 RPath("rpath",
9292 cl::desc("Set runtime shared library search path (requires -native or"
93 " -native-cbe)"),
93 " -native-cbe)"),
9494 cl::Prefix, cl::value_desc("directory"));
9595
9696 cl::opt
9797 SOName("soname",
9898 cl::desc("Set internal name of shared library (requires -native or"
99 " -native-cbe)"),
99 " -native-cbe)"),
100100 cl::Prefix, cl::value_desc("name"));
101101
102102 // Compatibility options that are ignored but supported by LD
154154
155155 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
156156 // shared object at all! See RH 8: plain text.
157 std::vector::iterator libc =
157 std::vector::iterator libc =
158158 std::find(Libraries.begin(), Libraries.end(), "c");
159159 if (libc != Libraries.end()) Libraries.erase(libc);
160160 // List all the shared object (native) libraries this executable will need
161161 // on the command line, so that we don't have to do this manually!
162 for (std::vector::iterator i = Libraries.begin(),
162 for (std::vector::iterator i = Libraries.begin(),
163163 e = Libraries.end(); i != e; ++i) {
164164 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
165165 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
177177 const cl::list& Files,
178178 const cl::list& Libraries) {
179179
180 // Build the list of linkage items for LinkItems.
180 // Build the list of linkage items for LinkItems.
181181
182182 cl::list::const_iterator fileIt = Files.begin();
183183 cl::list::const_iterator libIt = Libraries.begin();
230230
231231 // The libraries aren't linked in but are noted as "dependent" in the
232232 // module.
233 for (cl::list::const_iterator I = Libraries.begin(),
233 for (cl::list::const_iterator I = Libraries.begin(),
234234 E = Libraries.end(); I != E ; ++I) {
235235 TheLinker.getModule()->addLibrary(*I);
236236 }
266266 // strip debug info.
267267 int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
268268
269 // Internalize the module if neither -disable-internalize nor
269 // Internalize the module if neither -disable-internalize nor
270270 // -link-as-library are passed in.
271271 bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
272272
280280 Out.close();
281281
282282 // Generate either a native file or a JIT shell script. If the user wants
283 // to generate a native file, compile it from the bytecode file. Otherwise,
284 // if the target is not a library, create a script that will run the
283 // to generate a native file, compile it from the bytecode file. Otherwise,
284 // if the target is not a library, create a script that will run the
285285 // bytecode through the JIT.
286286 if (Native) {
287287 // Name of the Assembly Language output file
303303
304304 // Generate an assembly language file for the bytecode.
305305 if (Verbose) std::cout << "Generating Assembly Code\n";
306 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc,
306 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc,
307307 Verbose);
308308 if (Verbose) std::cout << "Generating Native Code\n";
309 GenerateNative(OutputFilename, AssemblyFile.toString(),
309 GenerateNative(OutputFilename, AssemblyFile.toString(),
310310 LibPaths, Libraries, gcc, envp, LinkAsLibrary, RPath,
311311 SOName, Verbose);
312312
0 //===- gccld.h - Utility functions header file ------------------*- 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 function prototypes for the functions in util.cpp.
3131 const sys::Path &llc,
3232 bool Verbose=false);
3333
34 int
35 GenerateCFile (const std::string &OutputFile,
34 int
35 GenerateCFile (const std::string &OutputFile,
3636 const std::string &InputFile,
3737 const sys::Path &llc,
3838 bool Verbose=false);
0 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 llc code generator driver. It provides a convenient
10 // command-line interface for generating native assembly-language code
10 // command-line interface for generating native assembly-language code
1111 // or C code, given LLVM bytecode.
1212 //
1313 //===----------------------------------------------------------------------===//
3131 // General options for llc. Other pass-specific options are specified
3232 // within the corresponding llc passes, and target-specific options
3333 // and back-end code generation options are specified with the target machine.
34 //
34 //
3535 static cl::opt
3636 InputFilename(cl::Positional, cl::desc(""), cl::init("-"));
3737
4242
4343 static cl::opt
4444 MArch("march", cl::desc("Architecture to generate assembly for:"));
45
45
4646 // GetFileNameRoot - Helper function to get the basename of a filename...
4747 static inline std::string
4848 GetFileNameRoot(const std::string &InputFilename) {
124124 OutputFilename = "-";
125125 Out = &std::cout;
126126 } else {
127 OutputFilename = GetFileNameRoot(InputFilename);
127 OutputFilename = GetFileNameRoot(InputFilename);
128128
129129 if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
130130 OutputFilename += ".s";
131131 else
132132 OutputFilename += ".cbe.c";
133
133
134134 if (!Force && std::ifstream(OutputFilename.c_str())) {
135135 // If force is not specified, make sure not to overwrite a file!
136136 std::cerr << argv[0] << ": error opening '" << OutputFilename
138138 << "Use -f command line argument to force output\n";
139139 return 1;
140140 }
141
141
142142 Out = new std::ofstream(OutputFilename.c_str());
143143 if (!Out->good()) {
144144 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
145145 delete Out;
146146 return 1;
147147 }
148
148
149149 // Make sure that the Out file gets unlinked from the disk if we get a
150150 // SIGINT
151151 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
0 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
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 utility provides a simple wrapper around the LLVM Execution Engines,
0 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
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 // Builds up (relatively) standard unix archive files (.a) containing LLVM
9 // Builds up (relatively) standard unix archive files (.a) containing LLVM
1010 // bytecode or other files.
1111 //
1212 //===----------------------------------------------------------------------===//
2323 using namespace llvm;
2424
2525 // Option for compatibility with ASIX, not used but must allow it to be present.
26 static cl::opt
27 X32Option ("X32_64", cl::Hidden,
26 static cl::opt
27 X32Option ("X32_64", cl::Hidden,
2828 cl::desc("Ignored option for compatibility with AIX"));
2929
3030 // llvm-ar operation code and modifier flags. This must come first.
31 static cl::opt
31 static cl::opt
3232 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
3333
3434 // llvm-ar remaining positional arguments.
35 static cl::list
36 RestOfArgs(cl::Positional, cl::OneOrMore,
35 static cl::list
36 RestOfArgs(cl::Positional, cl::OneOrMore,
3737 cl::desc("[relpos] [count] [members]..."));
3838
3939 // MoreHelp - Provide additional help output explaining the operations and
4040 // modifiers of llvm-ar. This object instructs the CommandLine library
4141 // to print the text of the constructor when the --help option is given.
4242 static cl::extrahelp MoreHelp(
43 "\nOPERATIONS:\n"
43 "\nOPERATIONS:\n"
4444 " d[NsS] - delete file(s) from the archive\n"
4545 " m[abiSs] - move file(s) in the archive\n"
4646 " p[kN] - print file(s) found in the archive\n"
8484 // Modifiers to follow operation to vary behavior
8585 bool AddAfter = false; ///< 'a' modifier
8686 bool AddBefore = false; ///< 'b' modifier
87 bool Create = false; ///< 'c' modifier
87 bool Create = false; ///< 'c' modifier
8888 bool TruncateNames = false; ///< 'f' modifier
8989 bool InsertBefore = false; ///< 'i' modifier
9090 bool DontSkipBytecode = false; ///< 'k' modifier
134134 throw "Expected [relpos] for a, b, or i modifier";
135135 }
136136
137 // getCount - Extract the [count] argument associated with the N modifier
137 // getCount - Extract the [count] argument associated with the N modifier
138138 // from the command line and check its value.
139139 void getCount() {
140140 if(RestOfArgs.size() > 0) {
163163 // This is just for clarity.
164164 void getMembers() {
165165 if(RestOfArgs.size() > 0)
166 Members = std::vector(RestOfArgs);
166 Members = std::vector(RestOfArgs);
167167 }
168168
169169 // parseCommandLine - Parse the command line options as presented and return the
170 // operation specified. Process all modifiers and check to make sure that
170 // operation specified. Process all modifiers and check to make sure that
171171 // constraints on modifier/operation pairs have not been violated.
172172 ArchiveOperation parseCommandLine() {
173173
187187 case 'd': ++NumOperations; Operation = Delete; break;
188188 case 'm': ++NumOperations; Operation = Move ; break;
189189 case 'p': ++NumOperations; Operation = Print; break;
190 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
190 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
191191 case 't': ++NumOperations; Operation = DisplayTable; break;
192192 case 'x': ++NumOperations; Operation = Extract; break;
193193 case 'c': Create = true; break;
219219 NumPositional++;
220220 break;
221221 case 'N':
222 getCount();
222 getCount();
223223 UseCount = true;
224224 break;
225225 default:
227227 }
228228 }
229229
230 // At this point, the next thing on the command line must be
230 // At this point, the next thing on the command line must be
231231 // the archive name.
232232 getArchive();
233233
273273 if (RecurseDirectories) {
274274 std::set content;
275275 path.getDirectoryContents(content);
276 for (std::set::iterator I = content.begin(), E = content.end();
276 for (std::set::iterator I = content.begin(), E = content.end();
277277 I != E; ++I) {
278278 if (I->isDirectory()) {
279279 std::set moreResults = recurseDirectories(*I);
287287 }
288288
289289 // buildPaths - Convert the strings in the Members vector to sys::Path objects
290 // and make sure they are valid and exist exist. This check is only needed for
290 // and make sure they are valid and exist exist. This check is only needed for
291291 // the operations that add/replace files to the archive ('q' and 'r')
292292 void buildPaths(bool checkExistence = true) {
293293 for (unsigned i = 0; i < Members.size(); i++) {
315315 void printSymbolTable() {
316316 std::cout << "\nArchive Symbol Table:\n";
317317 const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
318 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
318 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
319319 I != E; ++I ) {
320320 unsigned offset = TheArchive->getFirstFileOffset() + I->second;
321321 std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n";
329329 void doPrint() {
330330 buildPaths(false);
331331 unsigned countDown = Count;
332 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
332 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
333333 I != E; ++I ) {
334 if (Paths.empty() ||
334 if (Paths.empty() ||
335335 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
336336 if (countDown == 1) {
337337 const char* data = reinterpret_cast(I->getData());
338338
339339 // Skip things that don't make sense to print
340 if (I->isLLVMSymbolTable() || I->isSVR4SymbolTable() ||
341 I->isBSD4SymbolTable() || (!DontSkipBytecode &&
340 if (I->isLLVMSymbolTable() || I->isSVR4SymbolTable() ||
341 I->isBSD4SymbolTable() || (!DontSkipBytecode &&
342342 (I->isBytecode() || I->isCompressedBytecode())))
343343 continue;
344344
363363 // putMode - utility function for printing out the file mode when the 't'
364364 // operation is in verbose mode.
365365 void printMode(unsigned mode) {
366 if (mode & 004)
366 if (mode & 004)
367367 std::cout << "r";
368368 else
369369 std::cout << "-";
383383 // modification time are also printed.
384384 void doDisplayTable() {
385385 buildPaths(false);
386 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
386 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
387387 I != E; ++I ) {
388 if (Paths.empty() ||
388 if (Paths.empty() ||
389389 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
390390 if (Verbose) {
391391 // FIXME: Output should be this format:
405405 std::cout << " " << std::setw(4) << I->getUser();
406406 std::cout << "/" << std::setw(4) << I->getGroup();
407407 std::cout << " " << std::setw(8) << I->getSize();
408 std::cout << " " << std::setw(20) <<
408 std::cout << " " << std::setw(20) <<
409409 I->getModTime().toString().substr(4);
410410 std::cout << " " << I->getPath().toString() << "\n";
411411 } else {
422422 void doExtract() {
423423 buildPaths(false);
424424 unsigned countDown = Count;
425 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
425 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
426426 I != E; ++I ) {
427427 if (Paths.empty() ||
428428 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
467467 buildPaths(false);
468468 if (Paths.empty()) return;
469469 unsigned countDown = Count;
470 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
470 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
471471 I != E; ) {
472472 if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
473473 if (countDown == 1) {
503503 // the archive to find the member in question. If we don't find it, its no
504504 // crime, we just move to the end.
505505 if (AddBefore || InsertBefore || AddAfter) {
506 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
506 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
507507 I != E; ++I ) {
508508 if (RelPos == I->getPath().toString()) {
509509 if (AddAfter) {
522522
523523 // Scan the archive again, this time looking for the members to move to the
524524 // moveto_spot.
525 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
525 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
526526 I != E && !remaining.empty(); ++I ) {
527 std::set::iterator found =
527 std::set::iterator found =
528528 std::find(remaining.begin(),remaining.end(),I->getPath());
529529 if (found != remaining.end()) {
530 if (I != moveto_spot)
530 if (I != moveto_spot)
531531 TheArchive->splice(moveto_spot,*TheArchive,I);
532532 remaining.erase(found);
533533 }
559559 }
560560
561561 // doReplaceOrInsert - Implements the 'r' operation. This function will replace
562 // any existing files or insert new ones into the archive.
562 // any existing files or insert new ones into the archive.
563563 void doReplaceOrInsert() {
564564
565565 // Build the list of files to be added/replaced.
580580 // to replace.
581581
582582 std::set::iterator found = remaining.end();
583 for (std::set::iterator RI = remaining.begin(),
583 for (std::set::iterator RI = remaining.begin(),
584584 RE = remaining.end(); RI != RE; ++RI ) {
585585 std::string compare(RI->toString());
586586 if (TruncateNames && compare.length() > 15) {
591591 nm += slashpos + 1;
592592 len -= slashpos +1;
593593 }
594 if (len > 15)
594 if (len > 15)
595595 len = 15;
596596 compare.assign(nm,len);
597597 }
633633 // If we didn't replace all the members, some will remain and need to be
634634 // inserted at the previously computed insert-spot.
635635 if (!remaining.empty()) {
636 for (std::set::iterator PI = remaining.begin(),
636 for (std::set::iterator PI = remaining.begin(),
637637 PE = remaining.end(); PI != PE; ++PI) {
638638 TheArchive->addFileBefore(*PI,insert_spot);
639639 }
0 //===--- llvm-as.cpp - The low-level LLVM assembler -----------------------===//
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 utility may be invoked in the following manner:
1111 // llvm-as [options] - Read LLVM asm from stdin, write bytecode to stdout
1212 // llvm-as [options] x.ll - Read LLVM asm from the x.ll file, write bytecode
1313 // to the x.bc file.
14 //
14 //
1515 //===------------------------------------------------------------------------===
1616
1717 #include "llvm/Module.h"
2727
2828 using namespace llvm;
2929
30 static cl::opt
30 static cl::opt
3131 InputFilename(cl::Positional, cl::desc(""), cl::init("-"));
3232
3333 static cl::opt
4040 static cl::opt
4141 DumpAsm("d", cl::desc("Print assembly as parsed"), cl::Hidden);
4242
43 static cl::opt
43 static cl::opt
4444 NoCompress("disable-compression", cl::init(false),
4545 cl::desc("Don't compress the generated bytecode"));
4646
7171 std::cerr << Err;
7272 return 1;
7373 }
74
74
7575 if (DumpAsm) std::cerr << "Here's the assembly:\n" << *M.get();
7676
7777 if (OutputFilename != "") { // Specified an output filename?
8383 << "Use -f command line argument to force output\n";
8484 return 1;
8585 }
86 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
86 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
8787 std::ios::trunc | std::ios::binary);
8888 } else { // Specified stdout
8989 // FIXME: cout is not binary!
112112 return 1;
113113 }
114114
115 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
115 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
116116 std::ios::trunc | std::ios::binary);
117117 // Make sure that the Out file gets unlinked from the disk if we get a
118118 // SIGINT
119119 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
120120 }
121121 }
122
122
123123 if (!Out->good()) {
124124 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
125125 return 1;
126126 }
127
127
128128 if (Force || !CheckBytecodeOutputToConsole(Out,true)) {
129129 WriteBytecodeToFile(M.get(), *Out, !NoCompress);
130130 }
0 //===-- llvm-bcanalyzer.cpp - Byte Code Analyzer --------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
4 // This file was developed by Reid Spencer and is distributed under the
4 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This tool may be invoked in the following manner:
1212 //
1313 // Options:
1414 // --help - Output information about command line switches
15 // --nodetails - Don't print out detailed informaton about individual
15 // --nodetails - Don't print out detailed informaton about individual
1616 // blocks and functions
1717 // --dump - Dump low-level bytecode structure in readable format
1818 //
1919 // This tool provides analytical information about a bytecode file. It is
2020 // intended as an aid to developers of bytecode reading and writing software. It
21 // produces on std::out a summary of the bytecode file that shows various
21 // produces on std::out a summary of the bytecode file that shows various
2222 // statistics about the contents of the file. By default this information is
2323 // detailed and contains information about individual bytecode blocks and the
24 // functions in the module. To avoid this more detailed output, use the
24 // functions in the module. To avoid this more detailed output, use the
2525 // -nodetails option to limit the output to just module level information.
26 // The tool is also able to print a bytecode file in a straight forward text
27 // format that shows the containment and relationships of the information in
28 // the bytecode file (-dump option).
26 // The tool is also able to print a bytecode file in a straight forward text
27 // format that shows the containment and relationships of the information in
28 // the bytecode file (-dump option).
2929 //===----------------------------------------------------------------------===//
3030
3131 #include "llvm/Analysis/Verifier.h"
4747 static cl::opt Dump ("dump", cl::desc("Dump low level bytecode trace"));
4848 static cl::opt Verify ("verify", cl::desc("Progressively verify module"));
4949
50 int
50 int
5151 main(int argc, char **argv) {
5252 try {
53 cl::ParseCommandLineOptions(argc, argv,
53 cl::ParseCommandLineOptions(argc, argv,
5454 " llvm-bcanalyzer Analysis of ByteCode Dumper\n");
5555
5656 sys::PrintStackTraceOnErrorSignal();
7777 } catch (std::string& errmsg ) {
7878 verificationMsg = errmsg;
7979 }
80 if ( verificationMsg.length() > 0 )
80 if ( verificationMsg.length() > 0 )
8181 std::cerr << "Final Verification Message: " << verificationMsg << "\n";
8282 }
8383
8787 std::cerr << argv[0] << ": " << ErrorMessage << "\n";
8888 return 1;
8989 }
90
90
9191
9292 if (Out != &std::cout) {
9393 ((std::ofstream*)Out)->close();
0 //===- CLICommand.h - Classes used to represent commands --------*- 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 defines a small class hierarchy used to represent the various types
7373 /// removeOptionName - Eliminate one of the names for this option.
7474 ///
7575 void removeOptionName(const std::string &Name) {
76 unsigned i = 0;
76 unsigned i = 0;
7777 for (; OptionNames[i] != Name; ++i)
7878 assert(i+1 < OptionNames.size() && "Didn't find option name!");
7979 OptionNames.erase(OptionNames.begin()+i);
100100 BuiltinCLICommand(const std::string &ShortHelp, const std::string &LongHelp,
101101 void (CLIDebugger::*impl)(std::string&))
102102 : CLICommand(ShortHelp, LongHelp), Impl(impl) {}
103
103
104104 void runCommand(CLIDebugger &D, std::string &Arguments) {
105105 (D.*Impl)(Arguments);
106106 }
0 //===-- CLIDebugger.cpp - Command Line Interface to the Debugger ----------===//
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 //===----------------------------------------------------------------------===//
8 //
8 //
99 // This file contains the main implementation of the Command Line Interface to
1010 // the debugger.
1111 //
7676 addCommand("next", C = new BuiltinCLICommand(
7777 "Step program until it reaches a new source line, stepping over calls", "",
7878 &CLIDebugger::nextCommand));
79 addCommand("n", C);
79 addCommand("n", C);
8080
8181 addCommand("finish", new BuiltinCLICommand(
8282 "Execute until the selected stack frame returns",
9090 "Print backtrace of all stack frames, or innermost COUNT frames",
9191 "FIXME: describe. Takes 'n', '-n' or 'full'\n",
9292 &CLIDebugger::backtraceCommand));
93 addCommand("bt", C);
94
93 addCommand("bt", C);
94
9595 addCommand("up", new BuiltinCLICommand(
9696 "Select and print stack frame that called this one",
9797 "An argument says how many frames up to go.\n",
107107 "With no argument, print the selected stack frame. (See also 'info frame').\n"
108108 "An argument specifies the frame to select.\n",
109109 &CLIDebugger::frameCommand));
110 addCommand("f", C);
110 addCommand("f", C);
111111
112112 //===--------------------------------------------------------------------===//
113113 // Breakpoint related commands
116116 "Set breakpoint at specified line or function",
117117 "FIXME: describe.\n",
118118 &CLIDebugger::breakCommand));
119 addCommand("b", C);
119 addCommand("b", C);
120120
121121
122122 //===--------------------------------------------------------------------===//
186186 // Look up the command in the table.
187187 std::map::iterator CI =
188188 CommandTable.lower_bound(Command);
189
189
190190 if (Command == "") {
191191 throw "Null command should not get here!";
192192 } else if (CI == CommandTable.end() ||
206206 // If the next command is a valid completion of this one, we are
207207 // ambiguous.
208208 if (++CI2 != CommandTable.end() && isValidPrefix(Command, CI2->first)) {
209 std::string ErrorMsg =
209 std::string ErrorMsg =
210210 "Ambiguous command '" + Command + "'. Options: " + CI->first;
211211 for (++CI; CI != CommandTable.end() &&
212212 isValidPrefix(Command, CI->first); ++CI)
241241
242242 try {
243243 CLICommand *CurCommand;
244
244
245245 if (Command == "") {
246246 CurCommand = LastCommand;
247247 Arguments = LastArgs;
256256
257257 // Finally, execute the command.
258258 if (CurCommand)
259 CurCommand->runCommand(*this, Arguments);
259 CurCommand->runCommand(*this, Arguments);
260260
261261 } catch (int RetVal) {
262262 // The quit command exits the command loop by throwing an integer return
272272 std::cout << "ERROR: Debugger caught unexpected exception!\n";
273273 // Attempt to continue.
274274 }
275
275
276276 // Write the prompt to get the next bit of user input
277277 std::cout << Prompt;
278278 }
301301 std::cout << "Please answer y or n.\n" << Message << " (y or n) "
302302 << std::flush;
303303 }
304
304
305305 // Ran out of input?
306306 return false;
307307 }
0 //===- CLIDebugger.h - LLVM Command Line Interface Debugger -----*- 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 defines the CLIDebugger class, which implements a command line
6161 //
6262 std::string Prompt; // set prompt, show prompt
6363 unsigned ListSize; // set listsize, show listsize
64
64
6565 //===------------------------------------------------------------------===//
6666 // Data to support user interaction
6767 //
68
68
6969 /// CurrentFile - The current source file we are inspecting, or null if
7070 /// none.
7171 const SourceFile *CurrentFile;
0 //===-- Commands.cpp - Implement various commands for the CLI -------------===//
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 //
7 //===----------------------------------------------------------------------===//
8 //
6 //
7 //===----------------------------------------------------------------------===//
8 //
99 // This file implements many builtin user commands.
1010 //
1111 //===----------------------------------------------------------------------===//
9090 std::cout << " ->";
9191 }
9292
93 std::cout << "\t" << std::string(LineStart, LineEnd) << "\n";
93 std::cout << "\t" << std::string(LineStart, LineEnd) << "\n";
9494 return false;
9595 }
9696
114114 std::cout << getProgramInfo().getFunction(FuncDesc).getSymbolicName();
115115 else
116116 std::cout << "";
117
117
118118 CurrentFile = &FileDesc->getSourceText();
119
119
120120 std::cout << " at " << CurrentFile->getFilename() << ":" << LineNo;
121121 if (ColNo) std::cout << ":" << ColNo;
122122 std::cout << "\n";
166166 std::string Tok = getToken(Val);
167167 if (Tok.empty() || (isOnlyOption && !getToken(Val).empty()))
168168 throw std::string(Msg) + " expects an unsigned integer argument.";
169
169
170170 char *EndPtr;
171171 unsigned Result = strtoul(Tok.c_str(), &EndPtr, 0);
172172 if (EndPtr != Tok.c_str()+Tok.size())
178178 /// getOptionalUnsignedIntegerOption - This method is just like
179179 /// getUnsignedIntegerOption, but if the argument value is not specified, a
180180 /// default is returned instead of causing an error.
181 static unsigned
181 static unsigned
182182 getOptionalUnsignedIntegerOption(const char *Msg, unsigned Default,
183183 std::string &Val, bool isOnlyOption = true) {
184184 // Check to see if the value was specified...
200200 // FIXME: tokenizing by whitespace is clearly incorrect. Instead we should
201201 // honor quotes and other things that a shell would. Also in the future we
202202 // should support redirection of standard IO.
203
203
204204 std::vector Arguments;
205205 for (std::string A = getToken(Options); !A.empty(); A = getToken(Options))
206206 Arguments.push_back(A);
207207 Dbg.setProgramArguments(Arguments.begin(), Arguments.end());
208208 }
209
209
210210
211211 //===----------------------------------------------------------------------===//
212212 // Program startup and shutdown options
476476 // Figure out where the user wants a breakpoint.
477477 const SourceFile *File;
478478 unsigned LineNo;
479
479
480480 // Check to see if the user specified a line specifier.
481481 std::string Option = getToken(Options); // strip whitespace
482482 if (!Option.empty()) {
488488 // Build a line specifier for the current stack frame.
489489 throw "FIXME: breaking at the current location is not implemented yet!";
490490 }
491
491
492492 if (!File) File = CurrentFile;
493493 if (File == 0)
494494 throw "Unknown file to place breakpoint!";
495495
496496 std::cerr << "Break: " << File->getFilename() << ":" << LineNo << "\n";
497
497
498498 throw "breakpoints not implemented yet!";
499499 }
500500
541541 << SF.getLanguage().getSourceLanguageName() << "\n";
542542
543543 } else if (What == "sources") {
544 const std::map &SourceFiles =
544 const std::map &SourceFiles =
545545 getProgramInfo().getSourceFiles();
546546 std::cout << "Source files for the program:\n";
547547 for (std::map::const_iterator I =
606606 std::string Name = getToken(FirstPart);
607607 if (!getToken(FirstPart).empty())
608608 throw "Extra junk in line specifier after '" + Name + "'.";
609 SourceFunctionInfo *SFI =
609 SourceFunctionInfo *SFI =
610610 getCurrentLanguage().lookupFunction(Name, getProgramInfo(),
611611 TheRuntimeInfo);
612612 if (SFI == 0)
650650
651651 // Handle "list foo," correctly, by returning " " as the second token
652652 Options += " ";
653
653
654654 std::string FirstLineSpec = getToken(Options, ",");
655655 std::string SecondLineSpec = getToken(Options, ",");
656656 if (!getToken(Options, ",").empty())
688688 }
689689
690690 } else {
691 // Parse two line specifiers...
691 // Parse two line specifiers...
692692 const SourceFile *StartFile, *EndFile;
693693 unsigned StartLineNo, EndLineNo;
694694 parseLineSpec(FirstLineSpec, StartFile, StartLineNo);
0 //===- llvm-db.cpp - LLVM Debugger ----------------------------------------===//
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 utility implements a simple text-mode front-end to the LLVM debugger
3434 cl::desc("Add directory to the search for source files"));
3535 cl::alias SDA("d", cl::desc("Alias for --directory"),
3636 cl::aliasopt(SourceDirectories));
37
37
3838 cl::opt
3939 WorkingDirectory("cd", cl::desc("Use directory as current working directory"),
4040 cl::value_desc("directory"));
7272 Dbg.setWorkingDirectory(WorkingDirectory);
7373 for (unsigned i = 0, e = SourceDirectories.size(); i != e; ++i)
7474 D.addSourceDirectory(SourceDirectories[i]);
75
75
7676 if (!InputArgs.empty()) {
7777 try {
7878 D.fileCommand(InputArgs[0]);
0 //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
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 utility may be invoked in the following manner:
3030 InputFilename(cl::Positional, cl::desc(""), cl::init("-"));
3131
3232 static cl::opt
33 OutputFilename("o", cl::desc("Override output filename"),
33 OutputFilename("o", cl::desc("Override output filename"),
3434 cl::value_desc("filename"));
3535
3636 static cl::opt
5353 std::cerr << "bytecode didn't read correctly.\n";
5454 return 1;
5555 }
56
56
5757 if (OutputFilename != "") { // Specified an output filename?
5858 if (OutputFilename != "-") { // Not stdout?
5959 if (!Force && std::ifstream(OutputFilename.c_str())) {
0 //===- extract.cpp - LLVM function extraction utility ---------------------===//
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 utility changes the input module to only contain a single function,
2727 static cl::opt
2828 InputFilename(cl::Positional, cl::desc(""),
2929 cl::init("-"), cl::value_desc("filename"));
30
30
3131 static cl::opt
32 OutputFilename("o", cl::desc("Specify output filename"),
32 OutputFilename("o", cl::desc("Specify output filename"),
3333 cl::value_desc("filename"), cl::init("-"));
3434
3535 static cl::opt
8787 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
8888 } else { // Specified stdout
8989 // FIXME: cout is not binary!
90 Out = &std::cout;
90 Out = &std::cout;
9191 }
9292
9393 Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
0 //===- Optimize.cpp - Optimize a complete program -------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
4 // This file was developed by Reid Spencer and is distributed under the
4 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements all optimization of the linked module for llvm-ld.
5151 )
5252 );
5353
54 static cl::opt DisableInline("disable-inlining",
54 static cl::opt DisableInline("disable-inlining",
5555 cl::desc("Do not run the inliner pass"));
5656
5757 static cl::opt
6161 static cl::opt DisableInternalize("disable-internalize",
6262 cl::desc("Do not mark all symbols as internal"));
6363
64 static cl::opt Verify("verify",
64 static cl::opt Verify("verify",
6565 cl::desc("Verify intermediate results of all passes"));
6666
67 static cl::opt Strip("s",
67 static cl::opt Strip("s",
6868 cl::desc("Strip symbol info from executable"));
6969
70 static cl::alias ExportDynamic("export-dynamic",
70 static cl::alias ExportDynamic("export-dynamic",
7171 cl::aliasopt(DisableInternalize),
7272 cl::desc("Alias for -disable-internalize"));
7373
8080 static inline void addPass(PassManager &PM, Pass *P) {
8181 // Add the pass to the pass manager...
8282 PM.add(P);
83
83
8484 // If we are verifying all of the intermediate steps, add the verifier...
85 if (Verify)
85 if (Verify)
8686 PM.add(createVerifierPass());
8787 }
8888
8989 namespace llvm {
9090
91 /// Optimize - Perform link time optimizations. This will run the scalar
92 /// optimizations, any loaded plugin-optimization modules, and then the
91 /// Optimize - Perform link time optimizations. This will run the scalar
92 /// optimizations, any loaded plugin-optimization modules, and then the
9393 /// inter-procedural optimizations if applicable.
9494 void Optimize(Module* M) {
9595
9797 PassManager Passes;
9898
9999 // If we're verifying, start off with a verification pass.
100 if (Verify)
100 if (Verify)
101101 Passes.add(createVerifierPass());
102102
103103 // Add an appropriate TargetData instance for this module...
170170 }
171171
172172 std::vector plugins = LoadableModules;
173 for (std::vector::iterator I = plugins.begin(),
173 for (std::vector::iterator I = plugins.begin(),
174174 E = plugins.end(); I != E; ++I) {
175175 sys::DynamicLibrary dll(I->c_str());
176176 typedef void (*OptimizeFunc)(PassManager&,int);
177177 OptimizeFunc OF = OptimizeFunc(
178178 dll.GetAddressOfSymbol("RunOptimizations"));
179179 if (OF == 0) {
180 throw std::string("Optimization Module '") + *I +
180 throw std::string("Optimization Module '") + *I +
181181 "' is missing the RunOptimizations symbol";
182182 }
183183 (*OF)(Passes,OptLevel);
0 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
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 utility is intended to be compatible with GCC, and follows standard
4343 cl::desc(""));
4444
4545 static cl::opt OutputFilename("o", cl::init("a.out"),
46 cl::desc("Override output filename"),
46 cl::desc("Override output filename"),
4747 cl::value_desc("filename"));
4848
49 static cl::opt Verbose("v",
49 static cl::opt Verbose("v",
5050 cl::desc("Print information about actions taken"));
51
51
5252 static cl::list LibPaths("L", cl::Prefix,
53 cl::desc("Specify a library search path"),
53 cl::desc("Specify a library search path"),
5454 cl::value_desc("directory"));
5555
5656 static cl::list Libraries("l", cl::Prefix,
57 cl::desc("Specify libraries to link to"),
57 cl::desc("Specify libraries to link to"),
5858 cl::value_desc("library prefix"));
5959
60 static cl::opt LinkAsLibrary("link-as-library",
60 static cl::opt LinkAsLibrary("link-as-library",
6161 cl::desc("Link the .bc files together as a library, not an executable"));
6262
6363 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
7474
7575 static cl::optDisableCompression("disable-compression",cl::init(false),
7676 cl::desc("Disable writing of compressed bytecode files"));
77
77
7878 // Compatibility options that are ignored but supported by LD
79 static cl::opt CO3("soname", cl::Hidden,
79 static cl::opt CO3("soname", cl::Hidden,
8080 cl::desc("Compatibility option: ignored"));
8181
82 static cl::opt CO4("version-script", cl::Hidden,
82 static cl::opt CO4("version-script", cl::Hidden,
8383 cl::desc("Compatibility option: ignored"));
8484
85 static cl::opt CO5("eh-frame-hdr", cl::Hidden,
85 static cl::opt CO5("eh-frame-hdr", cl::Hidden,
8686 cl::desc("Compatibility option: ignored"));
8787
88 static cl::opt CO6("h", cl::Hidden,
88 static cl::opt CO6("h", cl::Hidden,
8989 cl::desc("Compatibility option: ignored"));
9090
9191 /// This is just for convenience so it doesn't have to be passed around
341341 LibPaths.push_back("/usr/X11R6/lib");
342342 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
343343 // shared object at all! See RH 8: plain text.
344 std::vector::iterator libc =
344 std::vector::iterator libc =
345345 std::find(Libraries.begin(), Libraries.end(), "c");
346346 if (libc != Libraries.end()) Libraries.erase(libc);
347347 // List all the shared object (native) libraries this executable will need
348348 // on the command line, so that we don't have to do this manually!
349 for (std::vector::iterator i = Libraries.begin(),
349 for (std::vector::iterator i = Libraries.begin(),
350350 e = Libraries.end(); i != e; ++i) {
351351 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
352352 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
364364 const cl::list& Files,
365365 const cl::list& Libraries) {
366366
367 // Build the list of linkage items for LinkItems.
367 // Build the list of linkage items for LinkItems.
368368
369369 cl::list::const_iterator fileIt = Files.begin();
370370 cl::list::const_iterator libIt = Libraries.begin();
400400 // Initial global variable above for convenience printing of program name.
401401 progname = sys::Path(argv[0]).getBasename();
402402 Linker TheLinker(progname, Verbose);
403
403
404404 // Set up the library paths for the Linker
405405 TheLinker.addPaths(LibPaths);
406406 TheLinker.addSystemPaths();
422422
423423 // The libraries aren't linked in but are noted as "dependent" in the
424424 // module.
425 for (cl::list::const_iterator I = Libraries.begin(),
425 for (cl::list::const_iterator I = Libraries.begin(),
426426 E = Libraries.end(); I != E ; ++I) {
427427 TheLinker.getModule()->addLibrary(*I);
428428 }
475475 if (Verbose) std::cout << "Generating Assembly Code\n";
476476 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
477477 if (Verbose) std::cout << "Generating Native Code\n";
478 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
478 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
479479 gcc, envp);
480480
481481 // Remove the assembly language file.
509509 } else {
510510 EmitShellScript(argv);
511511 }
512
512
513513 // Make the script executable...
514514 sys::Path(OutputFilename).makeExecutable();
515515
0 //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
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 utility may be invoked in the following manner:
6666 std::cerr << "\n";
6767 }
6868 } else {
69 std::cerr << "Bytecode file: '" << Filename.c_str()
69 std::cerr << "Bytecode file: '" << Filename.c_str()
7070 << "' does not exist.\n";
7171 }
7272
0 //===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
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 program is a utility that works like traditional Unix "nm",
1010 // that is, it prints out the names of symbols in a bytecode file,
1111 // along with some information about each symbol.
12 //
12 //
1313 // This "nm" does not print symbols' addresses. It supports many of
1414 // the features of GNU "nm", including its different output formats.
1515 //
3434 cl::desc("Specify output format"),
3535 cl::values(clEnumVal(bsd, "BSD format"),
3636 clEnumVal(sysv, "System V format"),
37 clEnumVal(posix, "POSIX.2 format"),
37 clEnumVal(posix, "POSIX.2 format"),
3838 clEnumValEnd), cl::init(bsd));
3939 cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
4040 cl::aliasopt(OutputFormat));
4141
42 cl::list
42 cl::list
4343 InputFilenames(cl::Positional, cl::desc(""),
4444 cl::ZeroOrMore);
4545
0 //===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
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 tools is meant for use with the various LLVM profiling instrumentation
2727 using namespace llvm;
2828
2929 namespace {
30 cl::opt
30 cl::opt
3131 BytecodeFile(cl::Positional, cl::desc(""),
3232 cl::Required);
3333
34 cl::opt
34 cl::opt
3535 ProfileDataFile(cl::Positional, cl::desc(""),
3636 cl::Optional, cl::init("llvmprof.out"));
3737
8686 // Figure out how many times each successor executed.
8787 std::vector > SuccCounts;
8888 const TerminatorInst *TI = BB->getTerminator();
89
89
9090 std::map::iterator I =
9191 EdgeFreqs.lower_bound(std::make_pair(const_cast(BB), 0U));
9292 for (; I != EdgeFreqs.end() && I->first.first == BB; ++I)
141141 unsigned long long TotalExecutions = 0;
142142 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
143143 TotalExecutions += FunctionCounts[i].second;
144
144
145145 std::cout << "===" << std::string(73, '-') << "===\n"
146146 << "LLVM profiling output for execution";
147147 if (PI.getNumExecutions() != 1) std::cout << "s";
148148 std::cout << ":\n";
149
149
150150 for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
151151 std::cout << " ";
152152 if (e != 1) std::cout << i+1 << ". ";
153153 std::cout << PI.getExecution(i) << "\n";
154154 }
155
155
156156 std::cout << "\n===" << std::string(73, '-') << "===\n";
157157 std::cout << "Function execution frequencies:\n\n";
158158
184184 // Sort by the frequency, backwards.
185185 std::sort(Counts.begin(), Counts.end(),
186186 PairSecondSortReverse());
187
187
188188 std::cout << "\n===" << std::string(73, '-') << "===\n";
189189 std::cout << "Top 20 most frequently executed basic blocks:\n\n";
190190
204204
205205 BlockFreqs.insert(Counts.begin(), Counts.end());
206206 }
207
207
208208 if (PI.hasAccurateEdgeCounts()) {
209209 std::vector > Counts;
210210 PI.getEdgeCounts(Counts);
214214 if (PrintAnnotatedLLVM || PrintAllCode) {
215215 std::cout << "\n===" << std::string(73, '-') << "===\n";
216216 std::cout << "Annotated LLVM code for the module:\n\n";
217
217
218218 ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
219219
220220 if (FunctionsToPrint.empty() || PrintAllCode)
0 //===-- llvm-ranlib.cpp - LLVM archive index generator --------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
4 // This file was developed by Reid Spencer and is distributed under the
4 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // Adds or updates an index (symbol table) for an LLVM archive file.
2020 using namespace llvm;
2121
2222 // llvm-ar operation code and modifier flags
23 static cl::opt
23 static cl::opt
2424 ArchiveName(cl::Positional, cl::Optional, cl::desc(""));
2525
2626 static cl::opt
3131 void printSymbolTable(Archive* TheArchive) {
3232 std::cout << "\nArchive Symbol Table:\n";
3333 const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
34 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
34 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
3535 I != E; ++I ) {
3636 unsigned offset = TheArchive->getFirstFileOffset() + I->second;
3737 std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n";
6666 throw std::string("Archive file does not exist");
6767
6868 std::string err_msg;
69 std::auto_ptr
69 std::auto_ptr
7070 AutoArchive(Archive::OpenAndLoad(ArchivePath,&err_msg));
7171 Archive* TheArchive = AutoArchive.get();
7272 if (!TheArchive)
0 //===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
11 //
2 //
2 //
33 // The LLVM Compiler Infrastructure
44 //
5 // This file was developed by Reid Spencer and is distributed under the
5 // This file was developed by Reid Spencer and is distributed under the
66 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
7 //
88 //===----------------------------------------------------------------------===//
99 //
1010 // This file implements the bulk of the LLVM Compiler Driver (llvmc).
4747 }
4848
4949 void DumpConfigData(CompilerDriver::ConfigData* cd, const std::string& type ){
50 std::cerr << "Configuration Data For '" << cd->langName << "' (" << type
50 std::cerr << "Configuration Data For '" << cd->langName << "' (" << type
5151 << ")\n";
5252 std::cerr << "PreProcessor: ";
5353 DumpAction(&cd->PreProcessor);
6363
6464 /// This specifies the passes to run for OPT_FAST_COMPILE (-O1)
6565 /// which should reduce the volume of code and make compilation
66 /// faster. This is also safe on any llvm module.
66 /// faster. This is also safe on any llvm module.
6767 static const char* DefaultFastCompileOptimizations[] = {
6868 "-simplifycfg", "-mem2reg", "-instcombine"
6969 };
7575 CompilerDriverImpl(ConfigDataProvider& confDatProv )
7676 : cdp(&confDatProv)
7777 , finalPhase(LINKING)
78 , optLevel(OPT_FAST_COMPILE)
78 , optLevel(OPT_FAST_COMPILE)
7979 , Flags(0)
8080 , machine()
8181 , LibraryPaths()
107107 /// @name Methods
108108 /// @{
109109 public:
110 virtual void setFinalPhase( Phases phase ) {
111 finalPhase = phase;
112 }
113
114 virtual void setOptimization( OptimizationLevels level ) {
115 optLevel = level;
110 virtual void setFinalPhase( Phases phase ) {
111 finalPhase = phase;
112 }
113
114 virtual void setOptimization( OptimizationLevels level ) {
115 optLevel = level;
116116 }
117117
118118 virtual void setDriverFlags( unsigned flags ) {
119 Flags = flags & DRIVER_FLAGS_MASK;
119 Flags = flags & DRIVER_FLAGS_MASK;
120120 }
121121
122122 virtual void setOutputMachine( const std::string& machineName ) {
193193 }
194194 }
195195
196 sys::Path MakeTempFile(const std::string& basename,
196 sys::Path MakeTempFile(const std::string& basename,
197197 const std::string& suffix ) {
198198 sys::Path result(TempDir);
199199 if (!result.appendFile(basename))
203203 return result;
204204 }
205205
206 Action* GetAction(ConfigData* cd,
207 const sys::Path& input,
206 Action* GetAction(ConfigData* cd,
207 const sys::Path& input,
208208 const sys::Path& output,
209209 Phases phase)
210210 {
242242 // Get specific options for each kind of action type
243243 StringVector& addargs = AdditionalArgs[phase];
244244 // Add specific options for each kind of action type
245 action->args.insert(action->args.end(), addargs.begin(),
245 action->args.insert(action->args.end(), addargs.begin(),
246246 addargs.end());
247247 }
248248 } else
262262 case 'f':
263263 if (*PI == "%fOpts%") {
264264 if (!fOptions.empty())
265 action->args.insert(action->args.end(), fOptions.begin(),
265 action->args.insert(action->args.end(), fOptions.begin(),
266266 fOptions.end());
267267 } else
268268 found = false;
296296 action->args.push_back(output.toString());
297297 } else if (*PI == "%opt%") {
298298 if (!isSet(EMIT_RAW_FLAG)) {
299 if (cd->opts.size() > static_cast(optLevel) &&
299 if (cd->opts.size() > static_cast(optLevel) &&
300300 !cd->opts[optLevel].empty())
301 action->args.insert(action->args.end(),
301 action->args.insert(action->args.end(),
302302 cd->opts[optLevel].begin(),
303303 cd->opts[optLevel].end());
304304 else
305 throw std::string("Optimization options for level ") +
305 throw std::string("Optimization options for level ") +
306306 utostr(unsigned(optLevel)) + " were not specified";
307307 }
308308 } else
334334 case 'M':
335335 if (*PI == "%Mopts%") {
336336 if (!MOptions.empty())
337 action->args.insert(action->args.end(), MOptions.begin(),
337 action->args.insert(action->args.end(), MOptions.begin(),
338338 MOptions.end());
339339 } else
340340 found = false;
354354 }
355355 if (!found) {
356356 // Did it even look like a substitution?
357 if (PI->length()>1 && (*PI)[0] == '%' &&
357 if (PI->length()>1 && (*PI)[0] == '%' &&
358358 (*PI)[PI->length()-1] == '%') {
359359 throw std::string("Invalid substitution token: '") + *PI +
360360 "' for command '" + pat->program.toString() + "'";
391391 "' is not executable.");
392392
393393 // Invoke the program
394 const char** Args = (const char**)
394 const char** Args = (const char**)
395395 alloca(sizeof(const char*)*(action->args.size()+2));
396396 Args[0] = action->program.toString().c_str();
397397 for (unsigned i = 1; i != action->args.size(); ++i)
420420 fullpath.setFile(link_item);
421421 if (fullpath.readable())
422422 return fullpath;
423 for (PathVector::iterator PI = LibraryPaths.begin(),
423 for (PathVector::iterator PI = LibraryPaths.begin(),
424424 PE = LibraryPaths.end(); PI != PE; ++PI) {
425425 fullpath.setDirectory(PI->toString());
426426 fullpath.appendFile(link_item);
430430 fullpath.appendSuffix("a");
431431 } else {
432432 fullpath.appendSuffix("bc");
433 if (fullpath.readable())
433 if (fullpath.readable())
434434 return fullpath;
435435 fullpath.elideSuffix();
436436 fullpath.appendSuffix("o");
437 if (fullpath.readable())
437 if (fullpath.readable())
438438 return fullpath;
439439 fullpath = *PI;
440440 fullpath.appendFile(std::string("lib") + link_item);
471471 // If we didn't find the file in any of the library search paths
472472 // we have to bail. No where else to look.
473473 if (fullpath.isEmpty()) {
474 err =
474 err =
475475 std::string("Can't find linkage item '") + link_item.toString() + "'";
476476 return false;
477477 }
493493 while ( LI != LE ) {
494494 if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
495495 if (err.empty()) {
496 err = std::string("Library '") + *LI +
496 err = std::string("Library '") + *LI +
497497 "' is not valid for linking but is required by file '" +
498498 fullpath.toString() + "'";
499499 } else {
505505 }
506506 } else if (err.empty()) {
507507 err = std::string(
508 "The dependent libraries could not be extracted from '") +
508 "The dependent libraries could not be extracted from '") +
509509 fullpath.toString();
510510 return false;
511511 }
533533 std::cerr << "OutputMachine = " << machine << "\n";
534534 InputList::const_iterator I = InpList.begin();
535535 while ( I != InpList.end() ) {
536 std::cerr << "Input: " << I->first << "(" << I->second
536 std::cerr << "Input: " << I->first << "(" << I->second
537537 << ")\n";
538538 ++I;
539539 }
570570 // Get the suffix of the file name
571571 const std::string& ftype = I->second;
572572
573 // If its a library, bytecode file, or object file, save
574 // it for linking below and short circuit the
573 // If its a library, bytecode file, or object file, save
574 // it for linking below and short circuit the
575575 // pre-processing/translation/assembly phases
576576 if (ftype.empty() || ftype == "o" || ftype == "bc" || ftype=="a") {
577 // We shouldn't get any of these types of files unless we're
577 // We shouldn't get any of these types of files unless we're
578578 // later going to link. Enforce this limit now.
579579 if (finalPhase != LINKING) {
580580 throw std::string(
592592 // for this kind of file.
593593 ConfigData* cd = cdp->ProvideConfigData(I->second);
594594 if (cd == 0)
595 throw std::string("Files of type '") + I->second +
596 "' are not recognized.";
595 throw std::string("Files of type '") + I->second +
596 "' are not recognized.";
597597 if (isSet(DEBUG_FLAG))
598598 DumpConfigData(cd,I->second);
599599
630630 } else if (finalPhase == PREPROCESSING) {
631631 throw cd->langName + " does not support pre-processing";
632632 } else if (action.isSet(REQUIRED_FLAG)) {
633 throw std::string("Don't know how to pre-process ") +
633 throw std::string("Don't know how to pre-process ") +
634634 cd->langName + " files";
635635 }
636636
637 // Short-circuit remaining actions if all they want is
637 // Short-circuit remaining actions if all they want is
638638 // pre-processing
639639 if (finalPhase == PREPROCESSING) { continue; };
640640
652652 actions.push_back(GetAction(cd,InFile,Output,TRANSLATION));
653653 }
654654 } else {
655 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"trans"));
655 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"trans"));
656656 actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
657657 InFile = TempFile;
658658 }
673673 } else if (finalPhase == TRANSLATION) {
674674 throw cd->langName + " does not support translation";
675675 } else if (action.isSet(REQUIRED_FLAG)) {
676 throw std::string("Don't know how to translate ") +
676 throw std::string("Don't know how to translate ") +
677677 cd->langName + " files";
678678 }
679679
716716 } else if (finalPhase == OPTIMIZATION) {
717717 throw cd->langName + " does not support optimization";
718718 } else if (action.isSet(REQUIRED_FLAG)) {
719 throw std::string("Don't know how to optimize ") +
719 throw std::string("Don't know how to optimize ") +
720720 cd->langName + " files";
721721 }
722722 }
761761 // Put the action on the list
762762 actions.push_back(action);
763763
764 // Short circuit the rest of the loop, we don't want to link
764 // Short circuit the rest of the loop, we don't want to link
765765 continue;
766766 }
767767
815815 // Add in all the linkage items we generated. This includes the
816816 // output from the translation/optimization phases as well as any
817817 // -l arguments specified.
818 for (PathVector::const_iterator I=LinkageItems.begin(),
818 for (PathVector::const_iterator I=LinkageItems.begin(),
819819 E=LinkageItems.end(); I != E; ++I )
820820 link->args.push_back(I->toString());
821821
0 //===- CompilerDriver.h - Compiler Driver -----------------------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
4 // This file was developed by Reid Spencer and is distributed under the
4 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file declares the CompilerDriver class which implements the bulk of the
2222 /// The driver's purpose is to make it easier for compiler writers and users
2323 /// of LLVM to utilize the compiler toolkits and LLVM toolset by learning only
2424 /// the interface of one program (llvmc).
25 ///
25 ///
2626 /// @see llvmc.cpp
2727 /// @brief The interface to the LLVM Compiler Driver.
2828 class CompilerDriver {
4242 enum Phases {
4343 PREPROCESSING, ///< Source language combining, filtering, substitution
4444 TRANSLATION, ///< Translate source -> LLVM bytecode/assembly
45 OPTIMIZATION, ///< Optimize translation result
45 OPTIMIZATION, ///< Optimize translation result
4646 ASSEMBLY, ///< Convert program to executable
4747 LINKING, ///< Link bytecode and native code
4848 NUM_PHASES ///< Always last!
9191 struct ConfigData {
9292 ConfigData();
9393 std::string version; ///< The version number.
94 std::string langName; ///< The name of the source language
94 std::string langName; ///< The name of the source language
9595 StringTable opts; ///< The o10n options for each level
9696 StringVector libpaths; ///< The library paths
9797 Action PreProcessor; ///< PreProcessor command line
104104 /// This pure virtual interface class defines the interface between the
105105 /// CompilerDriver and other software that provides ConfigData objects to
106106 /// it. The CompilerDriver must be configured to use an object of this
107 /// type so it can obtain the configuration data.
107 /// type so it can obtain the configuration data.
108108 /// @see setConfigDataProvider
109109 /// @brief Configuration Data Provider interface
110110 class ConfigDataProvider {
115115
116116 /// These flags control various actions of the compiler driver. They are
117117 /// used by adding the needed flag values together and passing them to the
118 /// compiler driver's setDriverFlags method.
118 /// compiler driver's setDriverFlags method.
119119 /// @see setDriverFlags
120120 /// @brief Driver specific flags
121121 enum DriverFlags {
162162 virtual void setOutputMachine(const std::string& machineName) = 0;
163163
164164 /// @brief Set the options for a given phase.
165 virtual void setPhaseArgs(Phases phase, const StringVector& opts) = 0;
165 virtual void setPhaseArgs(Phases phase, const StringVector& opts) = 0;
166166
167167 /// @brief Set Library Paths
168168 virtual void setIncludePaths(const StringVector& paths) = 0;
0 //===- ConfigLexer.h - ConfigLexer Declarations -----------------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
4 // This file was developed by Reid Spencer and is distributed under the
4 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file declares the types and data needed by ConfigLexer.l
3636 }
3737 virtual ~InputProvider();
3838 virtual unsigned read(char *buf, unsigned max_size) = 0;
39 virtual void error(const std::string& msg);
39 virtual void error(const std::string& msg);
4040 virtual void checkErrors();
4141
4242 private:
6161 FOPTS_SUBST, ///< The substitution item %fOpts%
6262 IN_SUBST, ///< The substitution item %in%
6363 INCLS_SUBST, ///< The substitution item %incls%
64 INTEGER, ///< An integer
64 INTEGER, ///< An integer
6565 LANG, ///< The name "lang" (and variants)
6666 LIBPATHS, ///< The name "libpaths" (and variants)
6767 LIBS, ///< The name "libs" (and variants)
0 //===- Configuration.cpp - Configuration Data Mgmt --------------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
4 // This file was developed by Reid Spencer and is distributed under the
4 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the parsing of configuration files for the LLVM Compiler
3333
3434 InputProvider::~InputProvider() {}
3535 void InputProvider::error(const std::string& msg) {
36 std::cerr << name << ":" << ConfigLexerState.lineNum << ": Error: " <<
36 std::cerr << name << ":" << ConfigLexerState.lineNum << ": Error: " <<
3737 msg << "\n";
3838 errCount++;
3939 }
5252 class FileInputProvider : public InputProvider {
5353 public:
5454 FileInputProvider(const std::string & fname)
55 : InputProvider(fname)
55 : InputProvider(fname)
5656 , F(fname.c_str()) {
5757 ConfigLexerInput = this;
5858 }
7070 std::ifstream F;
7171 };
7272
73 cl::opt DumpTokens("dump-tokens", cl::Optional, cl::Hidden,
73 cl::opt DumpTokens("dump-tokens", cl::Optional, cl::Hidden,
7474 cl::init(false), cl::desc("Dump lexical tokens (debug use only)."));
7575
7676 struct Parser
8989 InputProvider* provider;
9090 CompilerDriver::ConfigData* confDat;
9191
92 inline int next() {
92 inline int next() {
9393 token = Configlex();
94 if (DumpTokens)
94 if (DumpTokens)
9595 std::cerr << token << "\n";
9696 return token;
9797 }
9898
99 inline bool next_is_real() {
99 inline bool next_is_real() {
100100 next();
101101 return (token != EOLTOK) && (token != ERRORTOK) && (token != 0);
102102 }
116116 while (next_is_real()) {
117117 switch (token ) {
118118 case STRING :
119 case OPTION :
119 case OPTION :
120120 result += ConfigLexerState.StringVal;
121121 break;
122122 case SEPARATOR:
228228 case LIBS:
229229 parseLibs();
230230 break;
231 case NAME:
232 confDat->langName = parseName();
233 break;
234 case OPT1:
235 parseOptionList(confDat->opts[CompilerDriver::OPT_FAST_COMPILE]);
236 break;
237 case OPT2:
238 parseOptionList(confDat->opts[CompilerDriver::OPT_SIMPLE]);
239 break;
240 case OPT3:
241 parseOptionList(confDat->opts[CompilerDriver::OPT_AGGRESSIVE]);
242 break;
243 case OPT4:
244 parseOptionList(confDat->opts[CompilerDriver::OPT_LINK_TIME]);
245 break;
246 case OPT5:
231 case NAME:
232 confDat->langName = parseName();
233 break;
234 case OPT1:
235 parseOptionList(confDat->opts[CompilerDriver::OPT_FAST_COMPILE]);
236 break;
237 case OPT2:
238 parseOptionList(confDat->opts[CompilerDriver::OPT_SIMPLE]);
239 break;
240 case OPT3:
241 parseOptionList(confDat->opts[CompilerDriver::OPT_AGGRESSIVE]);
242 break;
243 case OPT4:
244 parseOptionList(confDat->opts[CompilerDriver::OPT_LINK_TIME]);
245 break;
246 case OPT5:
247247 parseOptionList(
248248 confDat->opts[CompilerDriver::OPT_AGGRESSIVE_LINK_TIME]);
249249 break;
250 default:
251 error("Expecting 'name' or 'optN' after 'lang.'");
250 default:
251 error("Expecting 'name' or 'optN' after 'lang.'");
252252 break;
253253 }
254254 }
294294 break;
295295 }
296296 next();
297 } while (token != SPACE && token != EOFTOK && token != EOLTOK &&
297 } while (token != SPACE && token != EOFTOK && token != EOLTOK &&
298298 token != ERRORTOK);
299299 return !str.empty();
300300 }
311311 case SPACE:
312312 next();
313313 /* FALL THROUGH */
314 default:
314 default:
315315 {
316316 std::string progname;
317317 if (parseProgramName(progname))
401401 if (next() != SEPARATOR)
402402 error("Expecting '.'");
403403 switch (next()) {
404 case COMMAND:
404 case COMMAND:
405405 parseCommand(confDat->Translator);
406406 break;
407407 case REQUIRED:
413413 case PREPROCESSES:
414414 if (parseBoolean())
415415 confDat->Translator.set(CompilerDriver::PREPROCESSES_FLAG);
416 else
416 else
417417 confDat->Translator.clear(CompilerDriver::PREPROCESSES_FLAG);
418418 break;
419419 case OUTPUT:
463463 confDat->Translator.clear(CompilerDriver::OUTPUT_IS_ASM_FLAG);
464464 break;
465465 default:
466 error(std::string("Expecting 'command', 'preprocesses', "
467 "'translates' or 'output' but found '") +
466 error(std::string("Expecting 'command', 'preprocesses', "
467 "'translates' or 'output' but found '") +
468468 ConfigLexerState.StringVal + "' instead");
469469 break;
470470 }
508508 case LINKER: parseLinker(); break;
509509 case EOLTOK: break; // just ignore
510510 case ERRORTOK:
511 default:
511 default:
512512 error("Invalid top level configuration item");
513513 break;
514514 }
547547 confFile.setDirectory(conf);
548548 confFile.appendFile(ftype);
549549 if (!confFile.readable())
550 throw std::string("Configuration file for '") + ftype +
550 throw std::string("Configuration file for '") + ftype +
551551 "' is not available.";
552552 } else {
553553 // Try the user's home directory
568568 confFile = sys::Path::GetLLVMDefaultConfigDir();
569569 confFile.appendFile(ftype);
570570 if (!confFile.readable()) {
571 throw std::string("Configuration file for '") + ftype +
571 throw std::string("Configuration file for '") + ftype +
572572 "' is not available.";
573573 }
574574 }
578578 confFile = configDir;
579579 confFile.appendFile(ftype);
580580 if (!confFile.readable())
581 throw std::string("Configuration file for '") + ftype +
581 throw std::string("Configuration file for '") + ftype +
582582 "' is not available.";
583583 }
584584 FileInputProvider fip( confFile.toString() );
585585 if (!fip.okay()) {
586 throw std::string("Configuration file for '") + ftype +
586 throw std::string("Configuration file for '") + ftype +
587587 "' is not available.";
588588 }
589589 result = new CompilerDriver::ConfigData();
602602 Configurations.clear();
603603 }
604604
605 CompilerDriver::ConfigData*
605 CompilerDriver::ConfigData*
606606 LLVMC_ConfigDataProvider::ProvideConfigData(const std::string& filetype) {
607607 CompilerDriver::ConfigData* result = 0;
608608 if (!Configurations.empty()) {
0 //===- Configuration.h - Configuration Data Mgmt ----------------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
4 // This file was developed by Reid Spencer and is distributed under the
4 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file declares the LLVMC_ConfigDataProvider class which implements the
2121 /// The driver's purpose is to make it easier for compiler writers and users
2222 /// of LLVM to utilize the compiler toolkits and LLVM toolset by learning only
2323 /// the interface of one program (llvmc).
24 ///
24 ///
2525 /// @see llvmc.cpp
2626 /// @brief The interface to the LLVM Compiler Driver.
2727 class LLVMC_ConfigDataProvider : public CompilerDriver::ConfigDataProvider {
3434 /// @{
3535 public:
3636 /// @brief Provide the configuration data to the CompilerDriver.
37 virtual CompilerDriver::ConfigData*
37 virtual CompilerDriver::ConfigData*
3838 ProvideConfigData(const std::string& filetype);
3939
4040 /// @brief Allow the configuration directory to be set
41 virtual void setConfigDir(const sys::Path& dirName) {
42 configDir = dirName;
41 virtual void setConfigDir(const sys::Path& dirName) {
42 configDir = dirName;
4343 }
4444
4545 private:
0 //===--- llvmc.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by Reid Spencer and is distributed under the
55 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This tool provides a single point of access to the LLVM compilation tools.
1010 // It has many options. To discover the options supported please refer to the
1111 // tools' manual page (docs/CommandGuide/html/llvmc.html) or run the tool with
1212 // the --help option.
13 //
13 //
1414 //===------------------------------------------------------------------------===
1515
1616 #include "CompilerDriver.h"
2727 //=== PHASE OPTIONS
2828 //===------------------------------------------------------------------------===
2929 cl::opt FinalPhase(cl::Optional,
30 cl::desc("Choose final phase of compilation:"),
30 cl::desc("Choose final phase of compilation:"),
3131 cl::init(CompilerDriver::LINKING),
3232 cl::values(
3333 clEnumValN(CompilerDriver::PREPROCESSING,"E",
7070 //===------------------------------------------------------------------------===
7171
7272 cl::list PreprocessorToolOpts("Tpre", cl::ZeroOrMore,
73 cl::desc("Pass specific options to the pre-processor"),
73 cl::desc("Pass specific options to the pre-processor"),
7474 cl::value_desc("option"));
7575
7676 cl::alias PreprocessorToolOptsAlias("Wp,", cl::ZeroOrMore,
110110 cl::desc("Pass through -W options to compiler tools"),
111111 cl::value_desc("option"));
112112
113 cl::list BOpt("B", cl::ZeroOrMore, cl::Prefix,
113 cl::list BOpt("B", cl::ZeroOrMore, cl::Prefix,
114114 cl::desc("Specify path to find llvmc sub-tools"),
115115 cl::value_desc("dir"));
116116
125125 cl::desc("Specify base name of libraries to link to"), cl::value_desc("lib"));
126126
127127 cl::list Includes("I", cl::Prefix,
128 cl::desc("Specify location to search for included source"),
128 cl::desc("Specify location to search for included source"),
129129 cl::value_desc("dir"));
130130
131131 cl::list Defines("D", cl::Prefix,
136136 //=== OUTPUT OPTIONS
137137 //===------------------------------------------------------------------------===
138138
139 cl::opt OutputFilename("o",
139 cl::opt OutputFilename("o",
140140 cl::desc("Override output filename"), cl::value_desc("file"));
141141
142142 cl::opt OutputMachine("m", cl::Prefix,
168168 cl::opt Verbose("verbose", cl::Optional, cl::init(false),
169169 cl::desc("Print out each action taken"));
170170
171 cl::alias VerboseAlias("v", cl::Optional,
171 cl::alias VerboseAlias("v", cl::Optional,
172172 cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));
173173
174 cl::opt Debug("debug", cl::Optional, cl::init(false),
174 cl::opt Debug("debug", cl::Optional, cl::init(false),
175175 cl::Hidden, cl::desc("Print out debugging information"));
176176
177177 cl::alias DebugAlias("d", cl::Optional,
257257 try {
258258
259259 // Parse the command line options
260 cl::ParseCommandLineOptions(argc, argv,
260 cl::ParseCommandLineOptions(argc, argv,
261261 " LLVM Compiler Driver (llvmc)\n\n"
262262 " This program provides easy invocation of the LLVM tool set\n"
263263 " and other compiler tools.\n"
0 //===- AnalysisWrappers.cpp - Wrappers around non-pass analyses -----------===//
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 pass wrappers around LLVM analyses that don't make sense to
5555 }
5656
5757 void print(std::ostream &OS) const {}
58
58
5959 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
6060 AU.setPreservesAll();
6161 }
0 //===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
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 several printers for various different types of graphs used
2626 std::string Filename = GraphName + ".dot";
2727 O << "Writing '" << Filename << "'...";
2828 std::ofstream F(Filename.c_str());
29
29
3030 if (F.good())
3131 WriteGraph(F, GT);
3232 else
4545 static std::string getGraphName(CallGraph *F) {
4646 return "Call Graph";
4747 }
48
48
4949 static std::string getNodeLabel(CallGraphNode *Node, CallGraph *Graph) {
5050 if (Node->getFunction())
5151 return ((Value*)Node->getFunction())->getName();
6464 }
6565
6666 void print(std::ostream &OS) const {}
67
67
6868 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
6969 AU.addRequired();
7070 AU.setPreservesAll();
0 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
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 // Optimizations may be specified an arbitrary number of times on the command
136136 // Create a new optimization pass for each one specified on the command line
137137 for (unsigned i = 0; i < OptimizationList.size(); ++i) {
138138 const PassInfo *Opt = OptimizationList[i];
139
139
140140 if (Opt->getNormalCtor())
141141 Passes.add(Opt->getNormalCtor()());
142142 else if (Opt->getTargetCtor()) {
0 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
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 tablegen backend is emits an assembly printer for the current target.
6363 struct AsmWriterInst {
6464 std::vector Operands;
6565 const CodeGenInstruction *CGI;
66
66
6767 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
6868
6969 /// MatchesAllButOneOp - If this instruction is exactly identical to the
197197 if (Operands[i] != Other.Operands[i])
198198 if (MismatchOperand != ~0U) // Already have one mismatch?
199199 return ~1U;
200 else
200 else
201201 MismatchOperand = i;
202202 }
203203 return MismatchOperand;
267267 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
268268 FirstInst.CGI->TheDef->getName(),
269269 FirstInst.Operands[i]));
270
270
271271 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
272272 AsmWriterInst &AWI = SimilarInsts[si];
273273 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
312312
313313 // If all of the instructions start with a constant string (a very very common
314314 // occurance), emit all of the constant strings as a big table lookup instead
315 // of requiring a switch for them.
315 // of requiring a switch for them.
316316 bool AllStartWithString = true;
317317
318318 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
322322 AllStartWithString = false;
323323 break;
324324 }
325
325
326326 if (AllStartWithString) {
327327 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
328328 // all machine instructions are necessarily being printed, so there may be
360360
361361 O << " switch (MI->getOpcode()) {\n"
362362 " default: return false;\n";
363
363
364364 while (!Instructions.empty())
365365 EmitInstructions(Instructions, O);
366366
0 //===- AsmWriterEmitter.h - Generate an assembly writer ---------*- 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 tablegen backend is responsible for emitting an assembly printer for the
2222 RecordKeeper &Records;
2323 public:
2424 AsmWriterEmitter(RecordKeeper &R) : Records(R) {}
25
25
2626 // run - Output the asmwriter, returning true on failure.
2727 void run(std::ostream &o);
2828 };
0 //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
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 // CodeEmitterGen uses the descriptions of instructions and their fields to
111111 }
112112 BI = NewBI;
113113 }
114
114
115115 unsigned Value = 0;
116116 const std::vector &Vals = R->getValues();
117117
129129
130130 DEBUG(o << " // " << *R->getValue("Inst") << "\n");
131131 o << " Value = " << Value << "U;\n\n";
132
132
133133 // Loop over all of the fields in the instruction, determining which are the
134 // operands to the instruction.
134 // operands to the instruction.
135135 unsigned op = 0;
136136 std::map OpOrder;
137137 std::map OpContinuous;
138138 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
139139 if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
140140 // Is the operand continuous? If so, we can just mask and OR it in
141 // instead of doing it bit-by-bit, saving a lot in runtime cost.
141 // instead of doing it bit-by-bit, saving a lot in runtime cost.
142142 BitsInit *InstInit = BI;
143143 int beginBitInVar = -1, endBitInVar = -1;
144144 int beginBitInInst = -1, endBitInInst = -1;
196196 // this is not an operand!!
197197 if (beginBitInInst != -1) {
198198 o << " // op" << op << ": " << Vals[i].getName() << "\n"
199 << " int64_t op" << op
199 << " int64_t op" << op
200200 <<" = getMachineOpValue(MI, MI.getOperand("<
201201 //<< " MachineOperand &op" << op <<" = MI.getOperand("<
202202 OpOrder[Vals[i].getName()] = op++;
203
204 DEBUG(o << " // Var: begin = " << beginBitInVar
203
204 DEBUG(o << " // Var: begin = " << beginBitInVar
205205 << ", end = " << endBitInVar
206206 << "; Inst: begin = " << beginBitInInst
207207 << ", end = " << endBitInInst << "\n");
208
208
209209 if (continuous) {
210210 DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()]
211211 << "\n");
212
212
213213 // Mask off the right bits
214214 // Low mask (ie. shift, if necessary)
215215 assert(endBitInVar >= 0 && "Negative shift amount in masking!");
219219 beginBitInVar -= endBitInVar;
220220 endBitInVar = 0;
221221 }
222
222
223223 // High mask
224224 o << " op" << OpOrder[Vals[i].getName()]
225225 << " &= (1<<" << beginBitInVar+1 << ") - 1;\n";
226
226
227227 // Shift the value to the correct place (according to place in inst)
228228 assert(endBi