Example #1
0
// FunctionName returns a unique function path and name.
// TODO refactor this code and everywhere it is called to remove duplication.
func FuncPathName(fn *ssa.Function) (path, name string) {
	rx := fn.Signature.Recv()
	pf := MakeID(rootProgram.Fset.Position(fn.Pos()).String()) //fmt.Sprintf("fn%d", fn.Pos())
	if rx != nil {                                             // it is not the name of a normal function, but that of a method, so append the method description
		pf = rx.Type().String() // NOTE no underlying()
	} else {
		if fn.Pkg != nil {
			pf = fn.Pkg.Object.Path() // was .Name(), but not unique
		}
	}
	return pf, fn.Name()
}
Example #2
0
func GetFnNameParts(fn *ssa.Function) (pack, nam string) {
	mName := fn.Name()
	pName, _ := FuncPathName(fn) //fmt.Sprintf("fn%d", fn.Pos()) //uintptr(unsafe.Pointer(fn)))
	if fn.Pkg != nil {
		if fn.Pkg.Object != nil {
			pName = fn.Pkg.Object.Path() // was .Name()
		}
	}
	if fn.Signature.Recv() != nil { // we have a method
		pName = fn.Signature.Recv().Pkg().Name() + ":" + fn.Signature.Recv().Type().String() // note no underlying()
		//pName = LanguageList[l].PackageOverloadReplace(pName)
	}
	return pName, mName
}
Example #3
0
func checkFn(fn *ssa.Function, prog *ssa.Program, ptrResult *pointer.Result, roots []*ssa.Function) {
	nam := fn.String()
	if strings.HasPrefix(strings.TrimPrefix(nam, "("), *prefix) {
		hasPath := false
		usedExternally := false
		for _, r := range roots {
			if r != nil {
				nod, ok := ptrResult.CallGraph.Nodes[r]
				if ok {
					//fmt.Println("NODE root", r.Name())
					pth := callgraph.PathSearch(nod,
						func(n *callgraph.Node) bool {
							if n == nil {
								return false
							}
							if n.Func == fn {
								for _, ine := range n.In {
									if ine.Caller.Func.Pkg != fn.Pkg {
										//fmt.Println("DEBUG diff? ",
										//	ine.Caller.Func.Pkg, fn.Pkg)
										usedExternally = true
										break
									}
								}
								return true
							}
							return false
						})
					if pth != nil {
						//fmt.Printf("DEBUG path from %v to %v = %v\n",
						//	r, fn, pth)
						hasPath = true
						break
					}
				}
			}
		}
		isUpper := unicode.IsUpper(rune(fn.Name()[0]))
		pos := fn.Pos()
		//if strings.HasPrefix(nam, "(") && (!hasPath || (!usedExternally && isUpper)) {
		//	fmt.Println("bad Pos", pos, prog.Fset.Position(pos).String())
		//}
		loc := strings.TrimPrefix(
			prog.Fset.Position(pos).String(),
			gopath+"/src/"+*prefix+"/")
		showFuncResult(loc, nam, hasPath, usedExternally, isUpper)
	}
	wg.Done()
}
Example #4
0
// prettyFunc pretty-prints fn for the user interface.
// TODO(adonovan): return HTML so we have more markup freedom.
func prettyFunc(this *types.Package, fn *ssa.Function) string {
	if fn.Parent() != nil {
		return fmt.Sprintf("%s in %s",
			types.TypeString(fn.Signature, types.RelativeTo(this)),
			prettyFunc(this, fn.Parent()))
	}
	if fn.Synthetic != "" && fn.Name() == "init" {
		// (This is the actual initializer, not a declared 'func init').
		if fn.Pkg.Pkg == this {
			return "package initializer"
		}
		return fmt.Sprintf("%q package initializer", fn.Pkg.Pkg.Path())
	}
	return fn.RelString(this)
}
Example #5
0
// FuncPathName returns a unique function path and name.
func (comp *Compilation) FuncPathName(fn *ssa.Function) (path, name string) {
	rx := fn.Signature.Recv()
	pf := tgoutil.MakeID(comp.rootProgram.Fset.Position(fn.Pos()).String()) //fmt.Sprintf("fn%d", fn.Pos())
	if rx != nil {                                                          // it is not the name of a normal function, but that of a method, so append the method description
		pf = rx.Type().String() // NOTE no underlying()
	} else {
		if fn.Pkg != nil {
			pf = fn.Pkg.Object.Path() // was .Name(), but not unique
		} else {
			goroot := tgoutil.MakeID(LanguageList[comp.TargetLang].GOROOT + string(os.PathSeparator))
			pf1 := strings.Split(pf, goroot) // make auto-generated names shorter
			if len(pf1) == 2 {
				pf = pf1[1]
			} // TODO use GOPATH for names not in std pkgs
		}
	}
	return pf, fn.Name()
}
Example #6
0
// visitFunc analyses function body.
func visitFunc(fn *ssa.Function, infer *TypeInfer, f *Function) {
	infer.Env.MigoProg.AddFunction(f.FuncDef)

	infer.Logger.Printf(f.Sprintf(FuncEnterSymbol+"───── func %s ─────", fn.Name()))
	defer infer.Logger.Printf(f.Sprintf(FuncExitSymbol+"───── func %s ─────", fn.Name()))
	if fn.Name() == "init" {
		if _, ok := f.Prog.InitPkgs[fn.Package()]; !ok {
			f.Prog.InitPkgs[fn.Package()] = true
		}
		f.hasBody = true
		return
	}
	for val, instance := range f.locals {
		infer.Logger.Printf(f.Sprintf(ParamSymbol+"%s = %s", val.Name(), instance))
		f.revlookup[instance.String()] = val.Name() // If it comes from params..
	}

	if fn.Blocks == nil {
		infer.Logger.Print(f.Sprintf(MoreSymbol + "« no function body »"))
		f.hasBody = false // No body
		return
	}
	// When entering function, always visit as block 0
	block0 := NewBlock(f, fn.Blocks[0], 0)
	visitBasicBlock(fn.Blocks[0], infer, f, block0, &Loop{Parent: f})
	f.hasBody = true
}
Example #7
0
func IsOverloaded(f *ssa.Function) bool {
	pn := "unknown" // Defensive, as some synthetic or other edge-case functions may not have a valid package name
	rx := f.Signature.Recv()
	if rx == nil { // ordinary function
		if f.Pkg != nil {
			if f.Pkg.Object != nil {
				pn = f.Pkg.Object.Path() //was .Name()
			}
		} else {
			if f.Object() != nil {
				if f.Object().Pkg() != nil {
					pn = f.Object().Pkg().Path() //was .Name()
				}
			}
		}
	} else { // determine the package information from the type description
		typ := rx.Type()
		ts := typ.String()
		if ts[0] == '*' {
			ts = ts[1:]
		}
		tss := strings.Split(ts, ".")
		if len(tss) >= 2 {
			ts = tss[len(tss)-2] // take the part before the final dot
		} else {
			ts = tss[0] // no dot!
		}
		pn = ts
	}
	tss := strings.Split(pn, "/") // TODO check this also works in Windows
	ts := tss[len(tss)-1]         // take the last part of the path
	pn = ts                       // TODO this is incorrect, but not currently a problem as there is no function overloading
	//println("DEBUG package name: " + pn)
	if LanguageList[TargetLang].FunctionOverloaded(pn, f.Name()) ||
		strings.HasPrefix(pn, "_") { // the package is not in the target language, signaled by a leading underscore and
		return true
	}
	return false
}
Example #8
0
func (l langType) FuncName(fnx *ssa.Function) string {
	pn := ""
	if fnx.Signature.Recv() != nil {
		pn = fnx.Signature.Recv().Type().String() // NOTE no use of underlying here
	} else {
		pn, _ = pogo.FuncPathName(fnx) //fmt.Sprintf("fn%d", fnx.Pos())
		fn := ssa.EnclosingFunction(fnx.Package(), []ast.Node{fnx.Syntax()})
		if fn == nil {
			fn = fnx
		}
		if fn.Pkg != nil {
			if fn.Pkg.Object != nil {
				pn = fn.Pkg.Object.Path() // was .Name()
			}
		} else {
			if fn.Object() != nil {
				if fn.Object().Pkg() != nil {
					pn = fn.Object().Pkg().Path() // was .Name()
				}
			}
		}
	}
	return l.LangName(pn, fnx.Name())
}
Example #9
0
File: ssa.go Project: hinike/llgo
func (u *unit) getFunctionLinkage(f *ssa.Function) llvm.Linkage {
	switch {
	case f.Pkg == nil:
		// Synthetic functions outside packages may appear in multiple packages.
		return llvm.LinkOnceODRLinkage

	case f.Parent() != nil:
		// Anonymous.
		return llvm.InternalLinkage

	case f.Signature.Recv() == nil && !ast.IsExported(f.Name()) &&
		!(f.Name() == "main" && f.Pkg.Object.Path() == "main") &&
		f.Name() != "init":
		// Unexported methods may be referenced as part of an interface method
		// table in another package. TODO(pcc): detect when this cannot happen.
		return llvm.InternalLinkage

	default:
		return llvm.ExternalLinkage
	}
}
Example #10
0
func (visit *visitor) function(fn *ssa.Function, isOvl isOverloaded) {
	if !visit.seen[fn] { // been, exists := visit.seen[fn]; !been || !exists {
		vprintln("DEBUG 1st visit to: ", fn.String())
		visit.seen[fn] = true
		visit.usesGR[fn] = false
		if isOvl(fn) {
			vprintln("DEBUG overloaded: ", fn.String())
			return
		}
		if len(fn.Blocks) == 0 { // exclude functions that reference C/assembler code
			// NOTE: not marked as seen, because we don't want to include in output
			// if used, the symbol will be included in the golibruntime replacement packages
			// TODO review
			vprintln("DEBUG no code for: ", fn.String())
			return // external functions cannot use goroutines
		}
		var buf [10]*ssa.Value // avoid alloc in common case
		for _, b := range fn.Blocks {
			for _, instr := range b.Instrs {
				for _, op := range instr.Operands(buf[:0]) {
					areRecursing := false
					afn, isFn := (*op).(*ssa.Function)
					if isFn {
						if afn == fn {
							areRecursing = true
						}
						visit.function(afn, isOvl)
						if visit.usesGR[afn] {
							vprintln("marked as using GR because referenced func uses GR")
							visit.usesGR[fn] = true
						}
						vprintln(fn.Name(), " calls ", afn.Name())
					}
					// TODO, review if this code should be included
					if !visit.usesGR[fn] {
						if _, ok := (*op).(ssa.Value); ok {
							typ := (*op).Type()
							typ = DeRefUl(typ)
							switch typ.(type) {
							// TODO use oracle techniques to determine which interfaces or functions may require GR
							case *types.Chan, *types.Interface:
								visit.usesGR[fn] = true // may be too conservative
								vprintln("marked as using GR because uses Chan/Interface")
							case *types.Signature:
								if !areRecursing {
									if !isFn {
										visit.usesGR[fn] = true
										vprintln("marked as using GR because uses Signature")
									}
								}
							}
						}
					}
				}
				if _, ok := instr.(*ssa.Call); ok {
					switch instr.(*ssa.Call).Call.Value.(type) {
					case *ssa.Builtin:
						//NoOp
					default:
						cc := instr.(*ssa.Call).Common()
						if cc != nil {
							afn := cc.StaticCallee()
							if afn != nil {
								visit.function(afn, isOvl)
								if visit.usesGR[afn] {
									visit.usesGR[fn] = true
									vprintln("marked as using GR because call target uses GR")
								}
								vprintln(fn.Name(), " calls ", afn.Name())
							}
						}
					}
				}
				if !visit.usesGR[fn] {
					switch instr.(type) {
					case *ssa.Go, *ssa.MakeChan, *ssa.Defer, *ssa.Panic,
						*ssa.Send, *ssa.Select:
						vprintln("usesGR because uses Go...", fn.Name())
						visit.usesGR[fn] = true
					case *ssa.UnOp:
						if instr.(*ssa.UnOp).Op.String() == "<-" {
							vprintln("usesGR because uses <-", fn.Name())
							visit.usesGR[fn] = true
						}
					}
				}
			}
		}
	}
}
Example #11
0
File: ssa.go Project: hinike/llgo
func (u *unit) defineFunction(f *ssa.Function) {
	// Only define functions from this package, or synthetic
	// wrappers (which do not have a package).
	if f.Pkg != nil && f.Pkg != u.pkg {
		return
	}

	llfn := u.resolveFunctionGlobal(f)
	linkage := u.getFunctionLinkage(f)

	isMethod := f.Signature.Recv() != nil

	// Methods cannot be referred to via a descriptor.
	if !isMethod {
		llfd := u.resolveFunctionDescriptorGlobal(f)
		llfd.SetInitializer(llvm.ConstBitCast(llfn, llvm.PointerType(llvm.Int8Type(), 0)))
		llfd.SetLinkage(linkage)
	}

	// We only need to emit a descriptor for functions without bodies.
	if len(f.Blocks) == 0 {
		return
	}

	ssaopt.LowerAllocsToStack(f)

	if u.DumpSSA {
		f.WriteTo(os.Stderr)
	}

	fr := newFrame(u, llfn)
	defer fr.dispose()
	fr.addCommonFunctionAttrs(fr.function)
	fr.function.SetLinkage(linkage)

	fr.logf("Define function: %s", f.String())
	fti := u.llvmtypes.getSignatureInfo(f.Signature)
	delete(u.undefinedFuncs, f)
	fr.retInf = fti.retInf

	// Push the compile unit and function onto the debug context.
	if u.GenerateDebug {
		u.debug.PushFunction(fr.function, f.Signature, f.Pos())
		defer u.debug.PopFunction()
		u.debug.SetLocation(fr.builder, f.Pos())
	}

	// If a function calls recover, we create a separate function to
	// hold the real function, and this function calls __go_can_recover
	// and bridges to it.
	if callsRecover(f) {
		fr = fr.bridgeRecoverFunc(fr.function, fti)
	}

	fr.blocks = make([]llvm.BasicBlock, len(f.Blocks))
	fr.lastBlocks = make([]llvm.BasicBlock, len(f.Blocks))
	for i, block := range f.Blocks {
		fr.blocks[i] = llvm.AddBasicBlock(fr.function, fmt.Sprintf(".%d.%s", i, block.Comment))
	}
	fr.builder.SetInsertPointAtEnd(fr.blocks[0])

	prologueBlock := llvm.InsertBasicBlock(fr.blocks[0], "prologue")
	fr.builder.SetInsertPointAtEnd(prologueBlock)

	// Map parameter positions to indices. We use this
	// when processing locals to map back to parameters
	// when generating debug metadata.
	paramPos := make(map[token.Pos]int)
	for i, param := range f.Params {
		paramPos[param.Pos()] = i
		llparam := fti.argInfos[i].decode(llvm.GlobalContext(), fr.builder, fr.builder)
		if isMethod && i == 0 {
			if _, ok := param.Type().Underlying().(*types.Pointer); !ok {
				llparam = fr.builder.CreateBitCast(llparam, llvm.PointerType(fr.types.ToLLVM(param.Type()), 0), "")
				llparam = fr.builder.CreateLoad(llparam, "")
			}
		}
		fr.env[param] = newValue(llparam, param.Type())
	}

	// Load closure, extract free vars.
	if len(f.FreeVars) > 0 {
		for _, fv := range f.FreeVars {
			fr.env[fv] = newValue(llvm.ConstNull(u.llvmtypes.ToLLVM(fv.Type())), fv.Type())
		}
		elemTypes := make([]llvm.Type, len(f.FreeVars)+1)
		elemTypes[0] = llvm.PointerType(llvm.Int8Type(), 0) // function pointer
		for i, fv := range f.FreeVars {
			elemTypes[i+1] = u.llvmtypes.ToLLVM(fv.Type())
		}
		structType := llvm.StructType(elemTypes, false)
		closure := fr.runtime.getClosure.call(fr)[0]
		closure = fr.builder.CreateBitCast(closure, llvm.PointerType(structType, 0), "")
		for i, fv := range f.FreeVars {
			ptr := fr.builder.CreateStructGEP(closure, i+1, "")
			ptr = fr.builder.CreateLoad(ptr, "")
			fr.env[fv] = newValue(ptr, fv.Type())
		}
	}

	// Allocate stack space for locals in the prologue block.
	for _, local := range f.Locals {
		typ := fr.llvmtypes.ToLLVM(deref(local.Type()))
		alloca := fr.builder.CreateAlloca(typ, local.Comment)
		fr.memsetZero(alloca, llvm.SizeOf(typ))
		bcalloca := fr.builder.CreateBitCast(alloca, llvm.PointerType(llvm.Int8Type(), 0), "")
		value := newValue(bcalloca, local.Type())
		fr.env[local] = value
		if fr.GenerateDebug {
			paramIndex, ok := paramPos[local.Pos()]
			if !ok {
				paramIndex = -1
			}
			fr.debug.Declare(fr.builder, local, alloca, paramIndex)
		}
	}

	// If this is the "init" function, enable init-specific optimizations.
	if !isMethod && f.Name() == "init" {
		fr.isInit = true
	}

	// If the function contains any defers, we must first create
	// an unwind block. We can short-circuit the check for defers with
	// f.Recover != nil.
	if f.Recover != nil || hasDefer(f) {
		fr.unwindBlock = llvm.AddBasicBlock(fr.function, "")
		fr.frameptr = fr.builder.CreateAlloca(llvm.Int8Type(), "")
	}

	term := fr.builder.CreateBr(fr.blocks[0])
	fr.allocaBuilder.SetInsertPointBefore(term)

	for _, block := range f.DomPreorder() {
		fr.translateBlock(block, fr.blocks[block.Index])
	}

	fr.fixupPhis()

	if !fr.unwindBlock.IsNil() {
		fr.setupUnwindBlock(f.Recover, f.Signature.Results())
	}

	// The init function needs to register the GC roots first. We do this
	// after generating code for it because allocations may have caused
	// additional GC roots to be created.
	if fr.isInit {
		fr.builder.SetInsertPointBefore(prologueBlock.FirstInstruction())
		fr.registerGcRoots()
	}
}